To mutate data in Firebase Data Connect, you can use the useDataConnectMutation hook.
import { useDataConnectMutation } from "@tanstack-query-firebase/react/data-connect";
import { createMovieRef } from "@dataconnect/default-connector";
function Component() {
const createMovie = useDataConnectMutation(
createMovieRef
);
return (
<button
disabled={createMovie.isPending}
onClick={() => {
createMovie.mutate({
title: 'John Wick',
genre: "Action",
imageUrl: "https://example.com/image.jpg",
});
}}
>
{createMovie.isPending ? "Creating..." : "Create Movie"}
</button>
);
}Additionally, you can provide a factory function to the mutation, which will be called with the mutation variables:
const createMovie = useDataConnectMutation((title: string) => createMovieRef({ title, reviewDate: Date.now() }));
// ...
createMovie.mutate("John Wick");The hook provides an additional mutation option called invalidate. This option accepts a list of query references which will be automatically invalidated when the mutation is successful.
const createMovie = useDataConnectMutation(createMovieRef, {
invalidate: [getMovieRef],
});The above example provides a getMovieRef instance to the invalidate array. By default this will invalidate all queries that cached via the getMovieRef reference, for example the following query references will be invalidated:
getMovieRef({ id: "1"});
getMovieRef({ id: "2"});You can also provide explicit references to the invalidate array, for example:
const createMovie = useDataConnectMutation(createMovieRef, {
invalidate: [getMovieRef({ id: "1" })],
});In this case only the query reference getMovieRef({ id: "1" }) will be invalidated.
Along with the data, the hook will also return the ref, source, and fetchTime metadata from the mutation.
const createMovie = useDataConnectMutation(createMovieRef);
const { dataConnectResult } = await createMovie.mutateAsync({
title: 'John Wick',
genre: "Action",
imageUrl: "https://example.com/image.jpg",
});
console.log(dataConnectResult.ref);
console.log(dataConnectResult.source);
console.log(dataConnectResult.fetchTime);