Home > database >  Trying to add an array of objects using react useState but getting the error 'Objects are not v
Trying to add an array of objects using react useState but getting the error 'Objects are not v

Time:04-18

I'm trying to add an array of objects using React useState but I keep getting the error

Objects are not valid as a React child (found: object with keys {})

This is my code in app.js Note: response.data is getting logged in the console, it's type is an object

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

useEffect(() => {
    Axios.get("http://localhost:3001/").then((response) => {
        setUsers([...users, response.data])
    }).catch((err) => console.log(err))
}, [])

This is the get api

app.get("/", (req, res) => {
    userModel.find({}, (err, result) => {
        if(!err) {
            res.json(result) //sends 'result' to front end
        } else {
            res.json(err)
        }})
})

The data (result) is being sent to the front end

This is the data I want to add

[{
    name: 'John',
    age: 20
},
    name: 'Doe',
    age: 23
}]

Edit: Simple arrays like [0,1,2] are getting added to users, arrays that contain objects arent being added

Edit 2: This is my whole function:

export default function App() {

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

    useEffect(() => {
        Axios.get("http://localhost:3001/").then((response) => {
            setUsers([...users, response.data])
        }).catch((err) => console.log(err))
    }, [])

    return(
        <>
            {users.map((user) => {
                return(
                    <div>
                        <h1>{user}</h1>
                    </div>
                )
            })}
        </>
    )
}

CodePudding user response:

You have to append the response.data as follows as @Thinker mentioned in the comment section.

useEffect(() => {
  Axios.get("http://localhost:3001/")
    .then((response) => {
      setUsers([...users, ...response.data]);
    })
    .catch((err) => console.log(err));
}, []);

And then you have to insert it in JSX properly. Currently you're directly giving an object inside <h1>{user}</h1> (It's a violation of JSX syntax). So correct it as follows to include user data correctly. (You can modify it as your preference)

                    <div>
                        <h1>{user.name}</h1>
                        <h1>{user.age}</h1>
                    </div>
  • Related