OpenReplay
Navigate back to the homepage
BLOG
Browse Repo
Back

Building an Encyclopedia with React and Wikipedia Search API

Ekekenta Odionyenfe . C
November 8th, 2021 · 3 min read

The evolution of APIs has drastically changed the way our applications are being developed to scale. One can build an API and reuse it in subsequent applications without having to reinvent the wheel. In this tutorial, I will be teaching you how to build an encyclopedia using Wikipedia search API. Great right? Let’s get started.

Getting started

I have already pushed the user interface with the components for this project to Github. Follow the steps below to get a copy of the code.

  1. Click on the Github link
  2. Download or Fork the repository to have a copy of it
  3. Unzip or clone the repository from your Github to your working directory
  4. Open your commad line
  5. Run npm install to install the required packages
  6. Run npm start to get the project started.

Wikipedia Search API

Wikipedia Search API is an Open-source search API, created by the Wikimedia Foundation to enable you to integrate a full-text search functionality in your projects. The API endpoint is in the form https://en.wikipedia.org/w/api.php?action=query&list=search&prop=info&inprop=url&utf8=&format=json&origin=*&srlimit=20&srsearch=word. Click on this link to know more about the API.

Making API Request

Open encyclopedia/components/Search.jsx , import react useState to handle our state changes and the Word component to display of the search results from the API.

1import Word from "./Words";
2import { useState } from "react";

Next, create a state to store the search results, the state will have an empty object by default.

1const [result, setResult] = useState({})

Next, we need to create a function to make a request to the API. This function will request the API with the word from the input field, then return the search word’s meanings. Before sending a request to the API, you remove all whitespaces from both sides of the input using the trim function, convert the input to lowercase using the toLowerCase function to get a make a uniform search.

1const trimVal = val.trim().toLowerCase();

Perhaps, we can check if the user is submitting empty data before you request the API using the fetch API.

1if (trimVal.length > 0) {
2 const api = `https://en.wikipedia.org/w/api.php?action=query&list=search&prop=info&inprop=url&utf8=&format=json&origin=*&srlimit=20&srsearch=${trimVal}`;
3 const response = await fetch(api);
4 if (!response.ok) {
5 throw Error(response.statusText)
6 }
7 return await response.json();
8}

Notice in our API endpoint, we interpolated the trimVal as a value to the srsearch parameter. This is because the srsearch parameter is responsible for searching for content matching its value. We check for the status of the request and throw an error when something goes wrong. Your fetchData function should look look this.

1async function fetchData(val) {
2 const trimVal = val.trim().toLowerCase();
3 if (trimVal.length > 0) {
4 const api = `https://en.wikipedia.org/w/api.php?action=quer y&list=search&prop=info&inprop=url&utf8=&format=json&origin =*&srlimit=20&srsearch=${trimVal}`;
5 const response = await fetch(api);
6 if (!response.ok) {
7 throw Error(response.statusText)
8 }
9 return await response.json();
10 }
11}

Next, we create a method to get the inputs from users. This function will collect the inputs from the users, and then call the fetchData we created earlier. The fetchData takes the value from the input as a parameter. We await the response from the API request and save the value to our state.

1async function handleSearch(e) {
2 const { value } = e.target;
3 setResult({ result: await fetchData(value) })
4 }

Finally, we need to listen to incoming events in our input field. When a user types a word, the handleSeach method will be called, which then requests the API for that particular word. We achieved this by listening to a keyUp event. Relace the input field with the code below.

1<input type="text" className="search" onKeyUp={handleSearch} />

Open Source Session Replay

Debugging a web application in production may be challenging and time-consuming. OpenReplay is an Open-source alternative to FullStory, LogRocket and Hotjar. It allows you to monitor and replay everything your users do and shows how your app behaves for every issue. It’s like having your browser’s inspector open while looking over your user’s shoulder. OpenReplay is the only open-source alternative currently available.

OpenReplay

Happy debugging, for modern frontend teams - Start monitoring your web app for free.

Display Results

Let’s display the search results to the user. We will create a separate component for the result, which you can find in the encyclopedia/components/Word.jsx. First, open encyclopedia/components/Search.jsx component, and send the search result to the Word component. We will check if the search returned a result before, sending the result to the Word component. This is a good practice to avoid errors when no search result is returned. Now, locate the division commented {/* Search result component */}, then add this code to it.

1<ul>
2 {result.result && result.result.query.search.map(data => <Word key={data.id} data={data} />)}
3 </ul>

Next, create a functional component Word component, which will be receiving the search results as props from the Search component.

1function Word(props) {
2 return (
3 <div className="listData">
4 </div>
5 )
6}
7export default Word;

Next, we need to get the listData element and append the search results to it.

1const searchList = document.querySelector(".listData");

When a request is made to the Wikipedia API, it returns a response like the one on the screenshot below.

Search Api Result Format

Perhaps, some of the search results from the API return a text with some HTML tags.

1"Vitamin <span class="searchmatch">D</span> is a group of fat-soluble secosteroids responsible for increasing intestinal absorption of calcium, magnesium, and phosphate, and many other"

So we need a way to parse the HTML tags and display them to the listData node. This is where the insertAdjacentHTML method comes to play. We use the insertAdjacentHTML method to parse the text from the search result and display it on the listData node. Then we get the title and the snippet, which are the searched word and the meaning respectively, we then display them to the user.

1searchList && searchList.insertAdjacentHTML("afterbegin",
2 `<li>
3 <h4>${props.data.title}</h4>
4 ${props.data.snippet}
5 </li>`);

Finally, let’s move to our browser, go to http://localhost:3000/ and search for a word.

Application search result

You can get the full project from Gitbub, the complete code is in the complateVersion branch.

Conclusion

In this tutorial, we learned how to build an encyclopedia using the React and Wikipedia Search API. We had an overview of what Wikipedia search API is all about and its implementation in our application. If you have any questions, feel free to reach out on Twitter.

More articles from OpenReplay Blog

Fetching Data from GraphQL APIs with Apollo React

Query your GraphQL database from your React App with a few lines of code thanks to Apollo React

November 8th, 2021 · 2 min read

Integrating OpenReplay with GitHub

Generate Github issues directly from the OpenReplay interface

November 5th, 2021 · 3 min read
© 2021 OpenReplay Blog
Link to $https://twitter.com/OpenReplayHQLink to $https://github.com/openreplay/openreplayLink to $https://www.linkedin.com/company/18257552