Home > Software design >  State does not update after axios call
State does not update after axios call

Time:02-05

My component looks like this:

import axios from "axios";
import React, { useState, useEffect } from "react";
import { Link } from 'react-router-dom'
import User from "./User";

const Users = () => {

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

    useEffect(() => {
        axios("http://localhost:8000/users")
        .then(response => setUsers(...response.data)})
        .catch(error => console.log(error))
    }, [users])

    return ( 
        <>
            <h1>All users</h1>
            <button className="btn btn-primary mb-2"><Link to="/users/create">Create</Link></button>
            <table className="table table-striped">
                <thead>
                    <tr>
                    <th scope="col">Name</th>
                    <th scope="col"></th>
                    <th scope="col">Created</th>
                    <th scope="col">Role</th>
                    <th scope="col">Action</th>
                    </tr>
                </thead>
                <tbody>
                    {users && users.map( user => <User user={user} key={user.id}/>)}

                </tbody>
            </table>
        </>
        
     );
}
 
export default Users;

When I refresh the page, I see the following error in the console

index.js:37 Uncaught TypeError: users.map is not a function

Note: if I log the users state in the console I can see the correct data.

What is wrong with my component?

CodePudding user response:

Get rid of the ... - you're splatting the response data array to multiple arguments, while setState only accepts one.

That means your users won't be an array, but just the first user.

Also get rid of the [users] dependency to avoid the infinite loop - just make it [].

CodePudding user response:

Where is the opening bracket?

also if you are going to set a state where you have and array you might want to do it like this

setState([...response.data]) This way it will keep it as an array. I don't know how you response.data is structured, but if it is an array then this will work.

what does this do

and also as @AKX said, remove the users from dependency because every time you setUsers the useEffect will be triggered to run and that is why you have your inifite loop

  •  Tags:  
  • Related