Building an Encyclopedia with React and Wikipedia Search API
Tags: react, javascript, webdev, tutorial
Published: 2021-11-08 08:58:39

_by author [Ekekenta Odionyenfe . C](https://blog.openreplay.com/authors/ekekenta-odionyenfe-c)_

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](https://github.com/icode247/encyclopedia) 
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](https://www.mediawiki.org/wiki/API:Search) 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. 

```javascript
import Word from "./Words";
import { useState } from "react";
```

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


```javascript
const [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.


```javascript
const trimVal = val.trim().toLowerCase();

```

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


```javascript
if (trimVal.length > 0) {
    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}`;
    const response = await fetch(api);
    if (!response.ok) {
       throw Error(response.statusText)
    }
    return await response.json();
}
```


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.


```javascript
async function fetchData(val) {
    const trimVal = val.trim().toLowerCase();
    if (trimVal.length > 0) {
        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}`;
        const response = await fetch(api);
        if (!response.ok) {
            throw Error(response.statusText)
        }
        return await response.json();
    }
}
```



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.


```javascript
    async function handleSearch(e) {
        const { value } = e.target;
        setResult({ result: await fetchData(value) })
    }
```

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.


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

## Open Source Session Replay
Debugging a web application in production may be challenging and time-consuming. [OpenReplay](https://github.com/openreplay/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](https://raw.githubusercontent.com/openreplay/openreplay/main/static/replayer.png)

Happy debugging, for modern frontend teams - [Start monitoring your web app for free](https://github.com/openreplay/openreplay).


     
## 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. 


```javascript
<ul>
    {result.result && result.result.query.search.map(data => <Word key={data.id} data={data} />)}
 </ul>
```


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


```javascript
function Word(props) {
  return (
    <div className="listData">
    </div>
  )
}
export default Word;
```


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


```javascript
const 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fgo67t4rj5ft7nt4bgl3.png)


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

```html
"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.


    
```javascript
searchList && searchList.insertAdjacentHTML("afterbegin",
    `<li>
        <h4>${props.data.title}</h4>
        ${props.data.snippet}
    </li>`);
```


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

![Application search result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/75ti8fe2dk1v4za45i8p.png)


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](https://twitter.com/EkekentaZion).