0

I want to get a JSON from a films API, I get the datas in the variable "data", but my array "allFilms" still empty even after the datas are loaded... (see the code below), Why my array is still empty please ?

const [allFilms, setAllFilms] = useState([]);
const [pending, setPending] = useState(true);
const [activePage, setActivePage] = useState(1)
const url = `https://api.themoviedb.org/3/movie/top_rated?api_key=${process.env.REACT_APP_API_KEY}&language=fr&page=${activePage}`;

useEffect(() => {
        loadAllFilms();
    }, []);

    async function loadAllFilms() {
        try {
            const data = await axios.get(url);
            console.log("data ", data); **<--- THIS CONSOLE.LOG GOT THE DATA**
            setAllFilms(data);
            console.log("allfilms ", allFilms); **<--- THIS CONSOLE.LOG IS EMPTY**
            setPending(false);
        } catch (error) {
            console.error(error);
    }
};
VersifiXion
  • 2,152
  • 5
  • 22
  • 40
  • Hi, you don't seem to be defining `allFilms` anywhere. What error are you getting? – hcs Jul 10 '19 at 17:56
  • @hcs the error i get is "TypeError: allFilms.map is not a function", but allFilms is defined in the first line as an empty array, and I fill the array with "setAllFilms(data);" – VersifiXion Jul 10 '19 at 17:58
  • 1
    You should actually show all code related to the error, you don't use `allFilms.map` here. – Dennis Vash Jul 10 '19 at 18:08
  • Yeah, looks like your allFilms is not an array. Check the response type – arnuga3 Jul 10 '19 at 18:12

1 Answers1

1

From your code, we only can guess that the error is due to your response type.

If it's a JSON array you should try:

const data = await axios.get(url);
setAllFilms(data.json);
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
  • it's resolved, in fact i should have put setAllFilms(data.data.results), cause the data i wanted to map on was on a sub-object results inside an object data who is itself a us object of another "data"... thank you – VersifiXion Jul 10 '19 at 18:11