I am trying to parse JSON object that I receive from API to array using useEffect. This is JSON data that I receive:
{
"results": [
{
"id": 1,
"email": "tmp@gmail.com",
"password": "$2b$10$AB0WHdpP.aEpMdEg780ssej",
"role": "student",
},
{
"id": 2,
"email": "tmp2@gmail.com",
"password": "$2b$10$nhhUL.angMUh6WhyCWp33.n",
"role": "mentor",
}
]
}
This is the part of the code where the parsing happens:
const [users, setUsers] = useState([])
useEffect(() => {
fetchUsers();
}, [])
// Fetch Users
const fetchUsers = async () => {
const res = await fetch(`http://localhost:3000/api/users`);
const data = await res.json();
console.log("Data:", data.data);
setUsers(data.data);
console.log("Users:", users);
}
Example of Console output that i recieve:
Data: (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]0: {id: 1, email: 'tmp@gmai.com', password: '$2b$10$AB0WHdpP.aEpMdEg780ssej', role: 'student'}1: {id: 2, email: 'tmp2@gmail.com', password: '$2b$10$nhhUL.angMUh6WhyCWp33.n', role: 'mentor'}length: 2[[Prototype]]: Array(0)
Users: []length: 0[[Prototype]]: Array(0)
Any suggestion on how should this be done or what is the issue will be appreciated.
>Solution :
There is no issue with your code.
The state updation in React is always asynchronous.
setUsers(data.data);
console.log("Users:", users);
Here setUsers will run asynchronously, hence control is moved to next line console.log("Users:",users) which is not yet updated and display its old value.
If you want to console.log() whenever users state changes use the following code
useEffect(()=> {
console.log('Users:',users);
},[users])