-
I have more context in a StackOverflow question: https://stackoverflow.com/q/70224567/3533365 I have a mock mutation like so: interface Person {
firstName: string;
lastName: string;
}
async function sendPersonApi({ firstName, lastName }: Person) {
await new Promise((res) => setTimeout(res, 1000));
return {
firstName,
lastName,
status: "success"
};
} I have two components: I have a CodeSandbox with this behavior mostly working: https://codesandbox.io/s/long-worker-k350q?file=/src/App.tsx Form const personAtom = atom<Person>({
firstName: "",
lastName: ""
});
function Form() {
const [formState, setFormState] = useAtom(personAtom);
const handleSubmit: FormEventHandler<HTMLFormElement> = useCallback(
(event) => {
event.preventDefault();
const formElement = event.currentTarget;
const formData = new FormData(formElement);
const firstName = formData.get("firstName") as string;
const lastName = formData.get("lastName") as string;
setFormState({ firstName, lastName }); // This does not update the `data`/`isLoading`/`isError` in the <Output /> component
},
[setFormState]
);
return (
<form id="name-form" onSubmit={handleSubmit}>
<input name="firstName" /> <br />
<input name="lastName" /> <br />
<button>Submit</button>
</form>
);
} Output function Output() {
const [person] = useAtom(personAtom);
const { mutate, data, isLoading, isError } = useMutation(sendPersonApi, {
mutationKey: "sendPerson"
});
useEffect(() => {
mutate(person);
}, [person]);
return (
<output name="name-output" form="name-form">
<p>data: {JSON.stringify(data)}</p>
<p>isLoading: {JSON.stringify(isLoading)}</p>
<p>isError: {JSON.stringify(isError)}</p>
</output>
);
} Initially, I had wanted to implement this by doing the mutation itself inside the So I ended up changing the implementation so that the submit handler just updates some global state (using The problem now though is that the Also, is there a cleaner way of using the result of a mutation in another component? I'd prefer to have the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
results of mutations are currently not shared across components like the results of queries are. To access loading states of a mutation globally, you can use usually, a mutation is somehow tied to a query. For example, in your case, you update the
|
Beta Was this translation helpful? Give feedback.
results of mutations are currently not shared across components like the results of queries are. To access loading states of a mutation globally, you can use
useIsMutating
and filter it by mutation key.usually, a mutation is somehow tied to a query. For example, in your case, you update the
user
entity, so usually, there is auseUserQuery
that tries to query the user data from the server. So instead of trying to use the response of the mutation and access this globally, what you can also do is:output
listen to theuserQuery
instead…