Skip to content
Advertisement

Updating react state when receiving an array of object

I am using an axios.get to make a call to my MongoDB. My response from the DB is an array of objects containing all the data from the database. I am only trying to save the username of each user to state. I am trying to set the response (res.data.username) to my state however when i log my state I am getting an empty array back. PS: There was no way to copy my response so i added an image of the response for reference, let me know if there’s a better way to show the response

The Response I am getting back

const [users, setUsers] = useState([]);
useEffect(() => {
    axios.get('http://localhost:5000/users')
    .then(res => {
        if (res.data.length > 0) {
            console.log(res.data)
            setUsers(user => [...user, res.data.username]);
        }
    })
    
}, [])

Advertisement

Answer

Since users is an array, Pass the array to setUsers. Use destructuring to for readability and simplification.

const [users, setUsers] = useState([]);
useEffect(() => {
  axios.get("http://localhost:5000/users").then((res) => {
    if (res.data.length > 0) {
      console.log(res.data);
      setUsers(res.data.map(({ username }) => username));
    }
  });
}, []);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement