I am attempting to set the initial value of the UseState as the first and last names of my users based on the response received 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 initially set the state of both firstname
and lastname
to empty strings.
In the form, I then set the default value to currentUser?.user?.firstname
and currentUser?.user?.lastname
. These values are correctly displayed in the form input fields.
https://i.sstatic.net/nv611.png
When I only change one field, the other remains an empty string because handleInput
has not been called on that field, thus not updating the input value to match the defaultValue
. Subsequently, when I submit the form, the unchanged input is overwritten with a blank string in the database.
Is there a way to correct this behavior so that when currentUser
is no longer null, we update the formData
from a blank string to the correct value?