En director.js,
Estoy tratando de obtener los datos de fetchAPI() de /api/index.js
y establecerlo como un estado.
Sin embargo, en recieveFetchApi(), después de la primera línea, el segundo console.log dice que el estado es una matriz vacía.
¿Qué estoy haciendo mal aquí? ¿Cómo puedo asegurarme de que el estado se ha establecido correctamente?
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; };