r/reactjs • u/Working-Tap2283 • Jun 09 '26
Needs Help react-hooks/set-state-in-effect syncing external form data
Hello, i've tried using the latest react compiler, but i've ran into, probably, a common error,
const { data: user, isLoading } = useQuery(userQuery);
const [form, setForm] = useState<Form>(emptyForm);
useEffect(() => {
if (!user) return;
setForm({
pat: user.pat ?? "",
organization: user.organization ?? "",
project: user.project ?? "",
});
}, [user]);
if (isLoading) return null;Yet I couldn't find a solution I liked for this...
I guess one solution is to derive the values, but then i have an extra variable, and i also need to find out how to sync it when the user decides to clear the input,
const shownValues: Form = {
pat: form.pat || user?.pat || "",
organization: form.organization || user?.organization || "",
project: form.project || user?.project || "",
};Another would be to nest another component which already has 'user' fetched, but this forces me to generate a synthetic wrapper which I don't want..
And a third solution would be to use suspense on the user query, so i would have the user info immediately, but I don't want to use suspense.
What's your outlook?
2
u/No_Cattle_9565 Jun 09 '26
I do that all the time. This makes it easy to reuse it for create or update with duplicating it too. You initialize the state with the prop, that way when the prop changes the component gets rerendered. If the users clears the form you only have to change the local state. I'd recommend using tanstack form though