I'm trying to populate the UseState initial value to the values of my users first and last name according to the response I got from the tRPC api.
const { data: sessionData } = useSession();
const { data: currentUser } = api.user.get.useQuery(
undefined, // no input
{ enabled: sessionData?.user !== undefined }
)
const [formData, setFormData] = useState({
firstname: "",
lastname: "",
});
const updateUser = api.user.update.useMutation()
const handleInput = (e: { target: { name: any; value: any; }; }) => {
const fieldName = e.target.name;
const fieldValue = e.target.value;
setFormData((prevState) => ({
...prevState,
[fieldName]: fieldValue
}));
console.log(formData)
}
I first initiate the state of both firstname and lastname to be an empty string.
In my form I then the default value currentUser?.user?.firstname and currentUser?.user?.lastname those values are set displayed correctly on the form input fields.
When I only change one of the fields the other remains an empty string because handleInput has not been called on that field, therefore never updating the input value to what the defaulValue is. When I then submit the form, the input that was never changed is overwritten to a blank string in the database.
Any way we can correct this behavior to that when currentUser is no longer null, we change the formData from a blank string to the correct value?

I figure out a way to do this, but I don't know if there is a better way of doing so.
Here is my solution: