Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parsing JSON object list to array in React

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading