Mutations
Learn how to mutate data in Firebase Data Connect using the Tanstack Query Firebase hooks.
Mutating Data
To mutate data in Firebase Data Connect, you can either use the generated injectors, or use the injectDataConnectMutation
injector.
import { injectCreateMovie } from "@firebasegen/movies/angular";
@Component({
...
template: `
<button
disabled={createMovie.isPending()}
(click)="addMovie()"
>
{{createMovie.isPending() ? "Creating..." : "Create Movie"}}
</button>
`
})
class AddMovieComponent() {
// Calls `injectDataConnectMutation` with the respective types.
// Alternatively:
// import { injectDataConnectMutation } from '@tanstack-query-firebase/angular/data-connect';
// ...
// createMovie = injectDataConnectMutation(createMovieRef);
createMovie = injectCreateMovie();
addMovie() {
createMovie.mutate({
title: 'John Wick',
genre: "Action",
imageUrl: "https://example.com/image.jpg",
});
}
}
Additionally, you can provide a factory function to the mutation, which will be called with the mutation variables:
createMovie = injectDataConnectMutation(undefined, () => ({
mutationFn: (title: string) => createMovieRef({ title, reviewDate: Date.now() })
}));
// ...
createMovie.mutate("John Wick");
Invalidating Queries
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 = injectDataConnectMutation(createMovieRef, {
invalidate: [getMovieRef],
});
Implicit references
// TODO(mtewani): Check this for Angular
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"});
Explicit references
You can also provide explicit references to the invalidate array, for example:
const createMovie = injectDataConnectMutation(createMovieRef, {
invalidate: [getMovieRef({ id: "1" })],
});
In this case only the query reference getMovieRef({ id: "1" })
will be invalidated.
Metadata
Along with the data, the hook will also return the ref
, source
, and fetchTime
metadata from the mutation.
const createMovie = injectDataConnectMutation(createMovieRef);
await createMovie.mutateAsync({
title: 'John Wick',
genre: "Action",
imageUrl: "https://example.com/image.jpg",
});
console.log(createMovie.dataConnectResult().ref);
console.log(createMovie.dataConnectResult().source);
console.log(createMovie.dataConnectResult().fetchTime);