Fetch Data from a Real API — React / JS- [Complete Step By Step]

Piyush Kumar
6 min readJul 19, 2022

Learn how we can fetch real data from real-world API using React/JS

Creating API key on TMDB

https://www.themoviedb.org/signup
Registration

After creating account verify it and Login now on:

https://www.themoviedb.org/login
login into account after verification

Get our API key: Profile & Settings > API

https://www.themoviedb.org/settings/api
API Key

Now we got our API Key and we will find out popular movies from the DB.

https://developers.themoviedb.org/3/getting-started/introduction
fetching popular categories movies

Replace with your API Key

https://developers.themoviedb.org/3/movies/get-popular-movies
Replace with our API key
E.g "https://api.themoviedb.org/3/movie/popular?api_key=19dedc791dc255XXXXXXXXXXXXXXXXXX&language=en-US&page=1"

Now our Aim is to grab those movies, so let's start the project: We are going here to create React Project

Setting up project

Let’s create an Application using Command Prompt

CMD > npx create-react-app movies

Now go to the movies folder…

cd movies

Please note I have deleted files src which are not needed for our project.

modified project

Let's modify our code:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
ReactDOM.render(<App />, document.getElementById("root"));

App.js

import React from 'react';
const App = () => {
return (
<div>
<h1>Hello App Component</h1>
</div>
);
};
export default App;

Running our Modified Project for the first time:

npm start

Output

Now we are going to fetch movies into App.js component using fetch() API of javascript. We are going to use async and await to handle the asynchronous data (Promise).

Let’s create an anonymous function to get movies from the API :

Once the Popular movies are fetched it is going to be stored inside a variable called ‘data’. Finally, this data coming from the API needs to be converted into JSON format, so we are going to convert it to JSON and store it into a variable called ‘movies’. Please note that is coming from the server will not on the same time to handle this we have used async and await keyword ensures to wait until the defined task gets executed.

When the page loads you want that API data on your webpage, to get this data we are going to make use hook called useEffect().

Whenever the component gets rendered we are going to use hook useEffect() i.e when the component gets rendered out, run the fetchPopular() function. The empty array [] written at the end of useEffect() ensures that it will load only for the first time i.e it runs when a piece of the state gets updated then this useEffect runs again and it may also help to avoid the infinite loop.

If you are familiar with React class lifecycle methods, you can think of useEffect() Hook is combination of componentDidMount, componentDidUpdate, and componentWillUnmount.

import React, { useEffect } from "react";
import "./App.css";
const App = () => {
const url =
"https://api.themoviedb.org/3/movie/popular?api_key=19dedc791dc255982eaf84be8a93012a&language=en-US&page=1";
useEffect(() => {
fetchPopular();
},[]);
const fetchPopular = async () => {
const data = await fetch(url);
const movies = await data.json();
console.log(movies);
};
return (
<div className="App">
<h1>Hello App Component</h1>
</div>
);
};
export default App;

→ You can see Movies output in the console of our Browser.

→ Now again to store that data somewhere, here we are stored in a little piece of state, which requires a hook called useState().

const [popular, setPopular] = useState([]);

Here popular is the variable and setPopular is actually a function that can be used to modify the data. The data that is we are getting from the movie database is in the form of an array of objects(see console), so empty array [] is passed in the useState().

Setting the list of movies available of results, because results object has all the data (see console):

const fetchPopular = async () => {
const data = await fetch(url);
const movies = await data.json();
console.log(movies);
setPopular(movies.results);
};

Loop over to popular movies using map() to get all data of movies.results. This will map and return each movie one by one.

return (
<div className="App">
<h1>Movies</h1>
{popular.map(movie => {
return <Movie />;
})}
</div>
);

First, let’s create a movie component.

// A component that return a Movie
import React from "react";const Movie = () => {
return (
<div>
<h5>Title</h5>
<img src="" alt="" />
</div>
);
};
export default Movie;

If Everything is correct we should output like this:

output for movies

Also if we check the console it has some data.

Now to get the Actual output we are going to use the Props in order to pass data from the Parent to Child component. Now we have to send data from Parent (App.js) to Child (Movie.jsx) so we are going to make use of Props.

As we get the different id for each movie we have used a key i.e key={ movie.id }

Sending data: Parent(App.js) to Child (Movie.jsx)
movie={movie}

Sending data to Movie.jsx

Receiving data: Child (Movie.jsx)

Final Output: Movies received from the API

In this way, we have successfully fetched the data from the movie database.

Code for Reference:-

index.js

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
ReactDOM.render(<App />, document.getElementById("root"));

App.js

import React, { useEffect, useState } from "react";
import "./App.css";
import Movie from "./Movie";
const App = () => {
const url =
"https://api.themoviedb.org/3/movie/popular?api_key=19dedc791dc255982eaf84be8a93012a&language=en-US&page=1";
const [popular, setPopular] = useState([]);
useEffect(() => {
fetchPopular();
}, []);
const fetchPopular = async () => {
const data = await fetch(url);
const movies = await data.json();
console.log(movies);
setPopular(movies.results);
};
return (
<div className="App">
<h1>Movies</h1>
<div className="popular-movies">
{popular.map((movie) => {
return <Movie key={movie.id} movie={movie} />;
})}
</div>
</div>
);
};export default App;

Movie.jsx

import React from "react";
const Movie = ({movie}) => {
return (
<div>
<h5>{movie.title}</h5>
<img src={"https://image.tmdb.org/t/p/w500" + movie.backdrop_path} alt={movie.path} />
</div>
);
};
export default Movie;

App.css

.App {
text-align: center;
}
.popular-movies {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
grid-column-gap: 1rem;
grid-row-gap: 2rem;
}
img {
width: 100%;
height: 30vh;
object-fit: cover;
border-radius: 1rem;
margin-bottom: 1rem;
}

index.css

body {
margin: 5% 20%;
}

Conclusion:

You just learn how to expose to real-world API using fetch() API and React.

Thank You

--

--