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