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

140
Views
Using async/promise with useeffect

I have json file which i load and i use Hook to SetState to it. After SetState i want to use state with Value of Json to my function. But my function is executing with null value because setState doesnt load before Execute function. Here is code

 const fetchQuestions = async () => {
        const data = await require("../../question.json");
        await setQuestions(
            data.map((item: IQuestion) => ({
                    id: item.id,
                    question: item.question,
                    answers: item.answers
                })
            ))
        await setQuestionsArray(
            data.map((item: IQuestion) => ({
                    id: item.id,
                    name: item.question
                })
            ))
        return questionsArray
    }

There is Function which i pass questionArray :

 const handleQuest = (array: Array<IArrayQuestion>) => {
        if (array.length > 0) {
            const numberArray = array.length
            const random = Math.floor(Math.random() * (numberArray - 0))
            const p = (array[random])
            setQuestion(p.name)
            setShuffleRandom(!shuffleRandom)
        }
    }

And i use it in useEffect

useEffect(() => {
        if (nick.length < 1) {
            navigate('/quiz')
        }
        fetchQuestions().then((res)=>{
            if (questionsArray.length > 0){
                handleQuest(res)
            }
            else{console.log("Nothing")}
        })
    }, [])

It still doesnt work. I dont have value in my function after promise

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Separate data fetching logic from your application components. First write fetchQuestions -

async function fetchQuestions() {
  const data = await require("../../questions.json")
  return data.map(item => ({
    id: item.id,
    question: item.question,
    answers: item.answers
  })
}

Your component shouldn't copy data to multiple states. There should be a single source of truth. You don't need multiple question arrays or a copy of the current question. Instead use derived (computed) state to reference the "current" question -

import { fetchQuestions } from "./api"

function MyComponent() {
  const [questions, setQuestions] = useState([])
  const [current, setCurrent] = useState(0)
  
  useEffect(async _ => {
    try {
      const q = await fetchQuestions()
      setQuestions(q)
      setCurrent(Math.floor(Math.random() * q.length)))
    }
    catch (err) {
      console.error(err.message)
    }
  ), [])

  return <div>
    <Question question={questions[current]} />
  </div>
}

Your Question component would look something like this -

function Question({ question }) {
  return <div data-question-id={question.id}>
    Q: {question.name}
    {question.answers.map((answer, key) =>
      <Answer key={key} answer={answer} />
    )}
  </div>
}

Write the Answer component, and so on ...

about 4 years ago · Juan Pablo Isaza Report

0

You need to add questionsArray in useEffect dependencies, but because it's a state, you should do it in two useEffects:

first fetch data:

useEffect(() => {
    if (nick.length < 1) {
        navigate('/quiz')
    }
    fetchQuestions()
}, [])

And in second useEffect:

useEffect(() => {
    if (questionsArray.length > 0){
        handleQuest(questionsArray)
    }
    else{console.log("Nothing")}
}, [questionsArray])

when questionsArray is in useEffect dependencies, with every fetch, it will refresh and new questions will be added.

about 4 years ago · Juan Pablo Isaza Report
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!