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": "[email protected]",
"password": "$2b$10$AB0WHdpP.aEpMdEg780ssej",
"role": "student",
},
{
"id": 2,
"email": "[email protected]",
"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: '[email protected]', password: '$2b$10$AB0WHdpP.aEpMdEg780ssej', role: 'student'}1: {id: 2, email: '[email protected]', 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.