What is the good ways to consume api in react. i am make file to handle api to get data. And i consume in another file, but that's make the data from api become undefined before return the real.
Movie.js
import {
useState,
useEffect
} from 'react';
import axios from 'axios';
const apiKey = 'apikey';
const url = 'https://api.themoviedb.org/3';
const Movie = {
GetMovieTrends() {
const [movies, setMovies] = useState({});
useEffect(() => {
axios.get(`${url}/trending/movie/day?api_key=${apiKey}`)
.then((response) => {
setMovies(response.data);
})
.catch((err) => {
console.log(err);
});
}, []);
return movies;
},
GetMovieGenres() {
const [genre, setGenre] = useState(null);
useEffect(() => {
axios.get(`${url}/genre/movie/list?api_key=${apiKey}`)
.then((response) => {
setGenre(response.data.genres);
})
.catch((err) => console.log(err));
}, []);
return genre;
}
};
export default Movie;
TrendContainer.jsx
import React from "react";
import MovieImage from "./movie/MovieImage";
import MovieTextContainer from "./movie/MovieTextContainer";
import Movie from '../models/Movie.js';
import CircularProgress from '@material-ui/core/CircularProgress';
import {
withStyles
} from '@material-ui/core/styles';
const WaitForMovie = withStyles(() => ({
root: {
color: '#212121',
width: '64px !important',
height: '64px !important',
},
}))(CircularProgress);
const TrendContainer = () => {
const movieTrends = Movie.GetMovieTrends().results;
return ( <
div >
<
h1 className = 'heading1 bottom-margin' > Movie Trending < /h1> <
div className = 'container-movie' > {
movieTrends === undefined ?
< WaitForMovie / >
:
movieTrends.slice(0, 7).map((movie) => {
return ( <
div className = 'wrap-card-movie bottom-margin'
key = {
movie.id
} >
<
MovieImage url = {
`https://image.tmdb.org/t/p/original/${movie.poster_path}`
}
name = {
movie.title
}
/> <
MovieTextContainer title = {
movie.original_title
}
idGenre = {
movie.genre_ids
}
/> <
/div>
);
})
} <
/div> <
/div>
);
};
export default TrendContainer;
You are violating the rules of hooks in your Movie component, the way it is currently setup should never work. The useState and useEfect hook must always be in the top level of a REACT function, not just a JS function.
But this could be an excellent example to use a custom hook in your application...
import { useState, useEffect } from 'react';
import axios from 'axios';
const API_KEY = 'apikey';
const API_URL = 'https://api.themoviedb.org/3';
const useMovies = ({apiKey = API_KEY, url = API_URL}) => {
const [ movies, setMovies ] = useState('');
const [ genre, setGenre ] = useState('');
useEffect(() => {
async function getMovieTrends(){
let movieData
try{
movieData = axios.get(`${url}/trending/movie/day?api_key=${apiKey}`)
}
catch(error) {
// don't keep this in production!!!!
console.log(error);
}
setMovies(movieData.data);
}
async function getMovieGenres(){
let genreData
try{
genreData = await axios.get(`${url}/genre/movie/list?api_key=${apiKey}`)
}
catch(error) {
// don't keep this in production!!!!
console.log(error)
}
setGenre(genreData?.data?.genres);
}
getMovieTrends();
getMovieGenres()
}, [apiKey, url]);
return {movies, genre}
}
export default useMovies;