Search code examples
reactjsaxiosfetch

Transform fetch in axios


I need to convert this code in my React project with fetch call, into an axios call and async/await.

The step that I follow are:

'npm install axios',

import axios from 'axios',

and after?

Someone can help me?

import React, { useState } from "react";
import { ResultCard } from "../ResultCard";

export const SearchMovie = () => {
    const [query, setQuery] = useState("");
    const [results, setResults] = useState([]);

    const onChange = (e) => {
        e.preventDefault();

        setQuery(e.target.value);
    
        fetch(
            `https://api.themoviedb.org/3/search/movie?api_key=${process.env.REACT_APP_TMDB_KEY}&language=en-US&page=1&include_adult=false&query=${e.target.value}`,
        )
            .then((res) => res.json())
            .then((data) => {
                if (!data.errors) {
                    setResults(data.results);
                } else {
                    setResults([]);
                }
            });
    };

    return (
        <div className="search-movie-page">
            <div className="container">
                <div className="search-movie-content">
                    <div className="input-wrapper">
                        <input type="text" placeholder="🔍 Search for a movie..." value={query} onChange={onChange} />
                    </div>
                    {results.length > 0 ? (
                        <ul className="results">
                            {results.map((movie) => (
                                <li key={movie.id}>
                                    <ResultCard movie={movie} />
                                </li>
                            ))}
                        </ul>
                    ) : (<h2 className="no-movies-found">Search Something<br/>or<br/>Check what you searched for</h2>)} 
                    </div>
            </div>
        </div>
    );
};

Solution

  • This...

    fetch(`https://api.themoviedb.org/3/search/movie?api_key=${
      process.env.REACT_APP_TMDB_KEY
      }&language=en-US&page=1&include_adult=false&query=${e.target.value}`)
      .then((res) => res.json())
      .then((data) => {
        if (!data.errors) { setResults(data.results); } else { setResults([]); }
      });
    

    ...must be turned into this...

    axios.get('https://api.themoviedb.org/3/search/movie', {
      params: {
        api_key: process.env.REACT_APP_TMDB_KEY,
        language: 'en-US',
        page: 1,
        include_adult: false,
        query: e.target.value,
      }
    })
    .then((data) => {
        if (!data.errors) { setResults(data.results); } else { setResults([]); }
    });
    

    Your original code does not have any error handling for failing requests. I recommend to add a catch to handle failing requests.

    .then((data) => { /* handle success */ })
    .catch((error) => { /* handle failure */ });