'setUser does not seem to get set when pulling from database
I am pulling in a user by ID and it seems like in the end it does pull from my database as it logs it all in the console but the state does not update the variables at all. I feel it is something small and stupid keeping me from getting just user 2 to show FirstName LastName - CollectorID | FinanceCompany next to the 2 under the header Update Collector.
import React, { useState, useEffect } from "react";
import axios from "axios";
import { useParams } from "react-router-dom";
const UpdateUser = () => {
const { CollectorID } = useParams();
const [user, setUser] = useState({
FirstName: '',
LastName: '',
CollectorCode: '',
FinanceCompany: ''
});
const { FirstName, LastName, CollectorCode, FinanceCompany } = user;
useEffect(() => {
loadUser();
}, []);// eslint-disable-line react-hooks/exhaustive-deps
const loadUser = async () => {
const result = await axios.get(`http://localhost:5000/getCollectors/${CollectorID}`);
setUser(result.data);
};
console.log(user);
return (
<div className="previewWrapper">
<h1>Update Collectors</h1>
<div className="wrapper">
{<div><p>{CollectorID} | {FirstName} {LastName} - {CollectorCode} | {FinanceCompany}</p></div>}
</div>
</div>
);
}
export default UpdateUser;
Solution 1:[1]
You expect object in your code however your API response is an array of objects. It's clearly visible from your logs.
To verify it you can simple try
setUser(result.data[0]); // instead of setUser(result.data);
This line below - always would result undefined values.
Since you are assigning an array, your variable destructuring like this would not work
const { FirstName, LastName, CollectorCode, FinanceCompany } = user;
.
You might want to change the logic how to store user data since API response and current state does not really match.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | n1md7 |

