Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

253
Views
state value is not set after using hooks. why?

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;
};

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!