React noob here.
I am having a hard time understanding how the useEffect and useState hooks work.
My App fetches data which upon retrieval needs to be rendered.
I am using the then() function to ensure that the variables are defined in the correct order. I have also tried using multiple useEffect() functions to guarantee the proper chronology. However, for whatever reason, my current variable is undefined. It is only defined on the first render.
import React, { useEffect, useState } from 'react'
export default function Answers() {
const [questions, setQuestions] = useState([])
const [current, setCurrent] = useState()
useEffect(() => {
fetch('http://localhost:8000/questions')
.then(res => res.json())
.then(data => setQuestions(data))
.then(setCurrent(questions[0]))
}, [])
return (
<div>
<ul>
{console.log(current['answers'])}
{current['answers'].map(item => <li>{item}</li>)}
</ul>
</div>
)
}
Here is the data being fetched:
{
"questions": [
{
"id": 1,
"question": "to work",
"answers": ["yapmak", "gitmek", "çalışmak", "gelmek"],
"correct": 3
},
{
"id": 2,
"question": "to know",
"answers": ["gitmek", "bilmek", "çalışmak", "gelmek"],
"correct": 2
},
{
"id": 3,
"question": "to want",
"answers": ["istemek", "gitmek", "çalışmak", "konuşmak"],
"correct": 1
}
]
}