Home > Net >  Parsing JSON object list to array in React
Parsing JSON object list to array in React

Time:09-19

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.

CodePudding user response:

You see Users as an empty array because it is an empty array when you log it. State update using the updater function provided by the useState hook is asynchronous, so the change will not be reflected immediately.

If you want to log the users array after state update, you can log it inside a useEffect hook with users as a dependency:

const [users, setUsers] = useState([])

  useEffect(() => {
    fetchUsers();
    }, [])

  useEffect(() => {
    console.log(users)
    }, [users])

  // 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);
  }

CodePudding user response:

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])
  • Related