In director.js,
I am trying to get the data from fetchAPI() from /api/index.js
and set it as a state.
However, in recieveFetchApi(), after the first line , the second console.log says the state is an empty array.
What am I doing wrong here? How can I make sure that the state is successfully set?
director.js
import React, { Component, useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { fetchAPI } from "../../api/index";
function Director() {
const [fetchedData, setfetchedData] = useState([]);
const [fetchedDirector, setfetchedDirector] = useState([]);
const recieveFetchApi = async (callback) => {
setfetchedData(await fetchAPI()); //why is this being called forever?maybe this MovieName thing is rerendering, so that is why
console.log(
"ok, recievedFetch did the job, after this, ill call the extractDirectors func"
);
console.log("now, fetchedData looks like this", fetchedData); //not set yet at this point. why?
callback();
};
useEffect(() => {
recieveFetchApi(function () {
extractDirectors();
});
}, []);
const extractDirectors = () => {
let directorArray = [];
for (let i = 0; i < fetchedData.length; i++) {
if (!directorArray.includes(fetchedData[i].director)) {
directorArray.push(fetchedData[i].director);
}
}
console.log("directorArray looks like this now", directorArray);
setfetchedDirector(directorArray);
};
return (
<div>
<h1>Search By Director</h1>
{fetchedDirector.map((director) => (
<p key={director}>{director}</p>
))}
</div>
);
}
export default Director;
/api/index.js
import axios from "axios";
export const fetchAPI = async () => {
let url = "https://ghibliapi.herokuapp.com/films";
const data = await axios.get(url);
console.log("the data we just got is like this", data.data);
return data.data;
};