Create a react component that fetches data

Viewed 48

I'd like to create a component that takes in an ID of a movie and from that ID I would be able to fetch data i would be able to get details from that movie. For example, in my moviecard component, I run this axios get to obtain data on a movie.

const Moviecard = (props) => {

const {movie} = props
  const [details, setDetails] = useState('')
  useEffect(()=> {    
    if(movie) {
      axios.get(`https://api.themoviedb.org/3/movie/${movie.id}?api_key=mykey&append_to_response=videos,images`).then(resp=> {
        setDetails(resp.data)
      })
      .catch(err=> { 
        console.log(err)
      })
    }
  }, [movie])

return (
  <div>Movie Card</div>
) 
}
export default Moviecard

So, I would like to create a component that only handles getting the data, and then importing that state which would contain all the data

1 Answers

Think this is where you would make your own custom hook, you can do something like

//useFetchMovie.js

export const useFetchMovie = (movieId) => {
  const [movieData, setMovieData] = useState({
    isLoading: true,
    error: false,
    data: null,
  });
  useEffect(() => {
    if (movieId) {
      axios
        .get(
          `https://api.themoviedb.org/3/movie/${movie.id}?api_key=mykey&append_to_response=videos,images`
        )
        .then((resp) => {
          setMovieData((oldMovieData) => ({
            ...oldMovieData,
            isLoading: false,
            data: resp.data,
          }));
        })
        .catch((err) => {
          setMovieData((oldMovieData) => ({
            ...oldMovieData,
            isLoading: false
            error: err,
          }));
        });
    }
  }, [movieId]);

  return movieData;
};

Related