Fetch api with ReactJs

Soheyb Merah
2 min readApr 17, 2020

--

You want to build an app that shows information related to a specific movie but you don’t work in Hollywood, so where you can get these information?

Thanks to Application programming interface or API you can have them without having access to the provider database.

For this project we will use omdbapi, make account and grab your key and save it, now we need to know how we can get data from omdb, go back to main page in Usage section we have what’s called an end point http://www.omdbapi.com/?apikey=[yourkey]&`so this is our main url that we are going to use, then under Parameters section because we want to search moveis by titles then we will focus on t.

Now we make a react app npx create-react-app movie-api you can change the project name movie-api.

We start by configuring our app to communicate with the api.

we make a search bar:

we implement the getJson method:

  • get the user input
var search = e.target.elements.searchItem.value;
  • we replace spaces with + (remember no space in url parameter ^^)
search = search.replace(" ", "+");
  • send get request to omdbapi to get our data , the search var has the user input and the API_KEY is your key (better to put it as var so the link don’t look large const API_KEY = 18151213 )
const api_call = await fetch(`http://www.omdbapi.com/?t=${search}&apikey=${API_KEY}`);const data = await api_call.json();

let’s explore our response request:

We take what we want and we organize them in the state variable

To get the title we only write:

<h1 className="d-flex justify-content-center mb-5">{this.state.title} // you can get the others same way ;)</h1>

Make a new components (optional) `<Main data={this.state} />` to set all what we had fetched:

If we don’t want to display the li element if we don’t have that data we use conditional rendering:

{data.actors && <li className="list-group-item">Actors: {data.actors}</li>}

Whenever you wan’t to consumer an API you only need an end point sometimes a key finally exploring it ^^, what next ? well you can explorer other API providers like open weather or alphavantage.

--

--

Soheyb Merah
Soheyb Merah

Written by Soheyb Merah

Computer Science Student enthusiast, who loves trying out new stuff, and contributing in Open Source Project, as I belive that teamwork is the key to success.

No responses yet