I'm trying to fetch data from an API and load that data onto a website using React. Currently, I am calling the fetch function using async and await. I printed out the results of the fetch call and all seems to be working properly. What I don't understand is why my studentsJSON array is still empty even though there is an array in data.students.
const [studentsJSON, setStudentsJSON] = useState([])
const [students, setStudents] = useState([])
useEffect(() => {
async function fetchData() {
const response = await fetch(URL)
const data = await response.json()
console.log(`data.students: ${data.students}`)
setStudentsJSON(data.students)
console.log(`studentsJSON: ${studentsJSON}`)
for (let student of studentsJSON) {
setStudents(students => [...students, new Student(student)])
}
console.log(`students: ${students}`)
}
fetchData()
}, [])
Output:
data.students: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
App.js:36 studentsJSON:
App.js:40 students:
useEffecthook to log the updated state:useEffect(() => { console.log(studentsJSON); }, [studentsJSON]);