Search code examples
reactjsuse-state

After fetching a list of objects from an API, how do I set the list into the Component's State using react hooks?


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..


Solution

  • 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.