i am try to fetch tha data from the api, the data is geting properly but while i set the data using state eg :- const data = setUser(data), than it’s showing the undefine
here is the code
import React, { useEffect, useState } from "react";
import axios from "axios";
// get request is placed here -------------------xxxxxxxxxxxxxxxxxxxx----------------------
function Student() {
const [users, setUsers] =useState();
useEffect(() => {
async function getStu() {
const res = await axios.get("http://localhost:5000/books");
const data = res;
setUsers(data)
console.log(users)
}
getStu();
}, []);
how to solve undefined error i watch so many youtube video but nothing is working
2
Answers
setState() is an async function . using
console.log()
just right after setting the new state will render the previous value in your case undefined . To show the new state move it to another useEffect hook .be aware when using axios , you send a request to the server it returns a response, Axios responses are objects. with data , status , StatusText , Headers … . if you want the
payload that the server returned
. you have to accessdata object
in your case res.data .In your case change your code like this :
There’s a few issues here.
Initialise your state with the type of data you’re expecting in the request whether it’s an array or an object etc.
You can’t immediately log an updated state as state updates are asynchronous and batched. Use a separate
useEffect
hook to log the state with the state listed in its dependency array.Axios returns an object with the API data as a value of the
data
property so you need to extract that.The other properties are the status/statusText etc which you may want to inspect to check that there isn’t an error with the response.