Skip to content

React API Fetch Guide

Introduction

This guide explains how to set up a React application and make API requests using both React’s Fetch method and Axios. We’ll use the DummyAPI’s Movies endpoint as an example.

Step 1: Create a New React App

Using Vite

If you prefer Vite:

Terminal window
npm create vite@latest my-react-app -- --template react
cd my-react-app
npm install

Using Bun

If you are using Bun:

Terminal window
bun create react my-react-app
cd my-react-app
bun install

Step 2: Install Axios (Optional)

To use Axios for API requests:

Terminal window
npm install axios

Or, if you’re using Bun:

Terminal window
bun add axios

Step 3: Setup Your React Component

Create a new component, e.g., src/components/MoviesComponent.jsx, and add the following code:

import { useState, useEffect } from 'react';
import axios from 'axios';
const MoviesComponent = () => {
const [movies, setMovies] = useState([]);
// Using Fetch
const fetchMovies = () => {
fetch('https://dummyapi.online/api/movies')
.then(response => response.json())
.then(data => setMovies(data))
.catch(error => console.error('Error:', error));
};
// Using Axios
const fetchMoviesWithAxios = () => {
axios.get('https://dummyapi.online/api/movies')
.then(response => setMovies(response.data))
.catch(error => console.error('Error:', error));
};
useEffect(() => {
fetchMovies(); // or fetchMoviesWithAxios();
}, []);
return (
<div>
<h1>Movies</h1>
<ul>
{movies.map(movie => (
<li key={movie.id}>{movie.movie}</li>
))}
</ul>
</div>
);
};
export default MoviesComponent;

Step 4: Include Your Component

Add MoviesComponent to your App.jsx:

import React from 'react';
import MoviesComponent from './components/MoviesComponent';
function App() {
return (
<div className="App">
<MoviesComponent />
</div>
);
}
export default App;

Step 5: Run Your App

Start your React application:

Terminal window
npm run dev # For Vite
# or
bun run start # For Bun

Step 6: View the Results

Open your browser and navigate to http://localhost:3000. You should see a list of movies fetched from the DummyAPI.

Conclusion

You’ve now set up a React application that can make API requests using both Fetch and Axios to the DummyAPI Movies endpoint. Explore further by integrating other endpoints and functionalities.