Home > Net >  After fetching a list of objects from an API, how do I set the list into the Component's State
After fetching a list of objects from an API, how do I set the list into the Component's State

Time:05-05

After fetching a list of students from an API, I want to set the list to the state using react hooks but I'm failing. Here's my code:

const Book = ({ book }) => {
const [students, setStudents] = React.useState([])
const [form, setForm] = React.useState(false)
const closeForm = () => setForm(false)

function loadStudentList(){
    fetch('http://127.0.0.1:8000/api/students/')
    .then((response) => response.json())
    .then(studentsList => {
        studentsList.map((student) => {
            setStudents(students => [...students, student])
        })
        setForm(true)
        console.log(students)
    })
}

console.log(students) returns an empty array still..

CodePudding user response:

const Book = ({ book }) => {
const [students, setStudents] = React.useState([])
const [form, setForm] = React.useState(false)
const closeForm = () => setForm(false)

function loadStudentList(){
    fetch('http://127.0.0.1:8000/api/students/')
    .then((response) => response.json())
    .then(studentsList => {
        setStudents(studentList)
        setForm(true)
    })
}

console.log(students)

From there, access students as needed in your React app.

CodePudding user response:

The students state will take some time to populate, so each of your setStudents(...) call will be queued up and run in a non-code-blocking fashion. This means that your console.log will be executed before the setting happens. You can get around this by creating a useEffect hook to monitor the students state and then consoling it out when it's populated. Try adding the below and see if it works!

useEffect(() => {
   if (students) console.log(students)
}, [students])

Additionally, you should be setting all the students at once as setStudents(studentsList)

  • Related