Home > other >  How to get an array of all movies from themoviedb?
How to get an array of all movies from themoviedb?

Time:01-05

I do not understand how to display all movies in an array. In console:

'index.jsx:14 GET https://api.themoviedb.org/3/movie/undefined?api_key=66eb3bde9cca0487f03e78b512b451e4 404
{success: false, status_code: 34, status_message: 'The resource you requested could not be found.'}'

My code is below:

import axios from "axios";
import React, { useEffect, useState } from "react";

const Main = () => {

    const [recipes, setRecipes] = useState([]);

    useEffect(() => {
        getRecipes()
    },[])

    const getRecipes = async (id) => {
        const response = await fetch(
          `https://api.themoviedb.org/3/movie/${id}?api_key=66eb3bde9cca0487f03e78b512b451e4`
        );
        const data = await response.json()
        setRecipes(data.id)
        console.log(data)
    }
      
    return(
        <main></main>
    )
}

export default Main;

CodePudding user response:

you didnt send an id to the getRecipes Function so it will cause an error, because the id is undefined at your function.

 useEffect(() => {
    getRecipes("2") //Here you should pass the id
},[])

Moreover , you imported axios without using it.

    const getRecipes = async (id) => {
    const response = await axios.get(`https://api.themoviedb.org/3/movie/${id}?api_key=66eb3bde9cca0487f03e78b512b451e4`);
    const data = response.data;
    console.log(data);
}

CodePudding user response:

I assume that you are looking for all movie list, not for a movie data. If that is what you meant be, then :-

As in the tmdb docs, you can discover movies, docs.

import axios from "axios";
import React, { useEffect, useState } from "react";

const Main = () => {

    const [recipes, setRecipes] = useState([]);

    useEffect(() => {
        getRecipes()
    },[])

    const getRecipes = async () => {
        const response = await fetch(
          `https://api.themoviedb.org/3/discover/movie?api_key=<your_api_key>`
        );
        const data = await response.json()
        setRecipes(data.results) // `results` from the tmdb docs
        console.log(data)
    }
      
    return(
        <main></main>
    )
}

export default Main;
  •  Tags:  
  • Related