skip to Main Content

I want to fetch all the movies data in API when my movie app starts

I tried using fetch function I used in search box ,to see If the data is correctly getting fetched I am tying to see it on ‘console.log’, but it throws an error

(intermediate value) is not iterable
TypeError: (intermediate value) is not iterable

Here is what I tried:

const fetchMovies = async () => {
            const [ res ] = await fetch(`${API_URL}`);
            const dat = await res.json();
            console.log(dat);
    }
useEffect(() => {
    fetchMovies() 
}, []);

2

Answers


  1. The response from await fetch is not an array but rather an object so you got the error.
    Remove the square bracket – [] and you will be fine.

    const fetchMovies = async () => {
        const res = await fetch(`${API_URL}`);
        const dat = await res.json();
        console.log(dat);
    }
    

    You can read more about fetch here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

    Login or Signup to reply.
  2. you can simply resolve the Promise using .then

    const fetchMovies = async () => {
            await fetch(`${API_URL}`)
            .then(res => {
               return res.json();
            })
            .then(resp => console.log(resp, 'movies'))
            .catch(err => console.log(err, 'error'))
    }
    useEffect(() => {
       fetchMovies() 
    }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search