I am using Firebase cloud REST API with redux toolkit query, I want to ask if I can create a new doc with a custom ID.
The following code works, but firebase generates an auto-id.
const baseQuery = fetchBaseQuery({
baseUrl:
"https://firestore.googleapis.com/v1/projects/[project-id]/databases/(default)/documents",
});
const userApi = createApi({
baseQuery: baseQuery,
reducerPath: "users",
endpoints: (builder) => ({
createUser: builder.mutation({
query: (userInfo: RegisterUser) => ({
url: `/users`,
method: "POST",
body: {
fields: {
email: { stringValue: userInfo.email },
fullname: { stringValue: userInfo.fullname },
trips: {
arrayValue: [],
},
},
},
}),
}),
But what if I want a custom ID that I send with the request?
I tried the following code by adding the id to the URL:
const baseQuery = fetchBaseQuery({
baseUrl:
"https://firestore.googleapis.com/v1/projects/[project-id]/databases/(default)/documents",
});
const userApi = createApi({
baseQuery: baseQuery,
reducerPath: "users",
endpoints: (builder) => ({
createUser: builder.mutation({
query: (userInfo: RegisterUser) => ({
url: `/users/${userInfo.id}` //added the id here,
method: "POST",
body: {
fields: {
email: { stringValue: userInfo.email },
fullname: { stringValue: userInfo.fullname },
trips: {
arrayValue: [],
},
},
},
}),
}),
And I got the following error :
{
"error": {
"code": 404,
"message": "Document "projects/[project-id/databases/(default)/documents/users/randomId" not found.",
"status": "NOT_FOUND"
}
}
When you define a URL like below:
url: `/users`
It means that you tell Firestore to add a document to the “users” collection using a random document ID. This is happening because you aren’t specifying any document ID in the addition operation at all.
But what if I want a custom ID that I send with the request?
To solve this, please note that the Firestore REST API allows you to create a document with a custom ID, if you specify the full document reference in the URL. So, instead of sending a request to the “users” collection, you can include the custom document ID directly in the URL:
So assuming you have a user
object, to write the data using the corresponding uid
, please use:
const baseQuery = fetchBaseQuery({
baseUrl:
"https://firestore.googleapis.com/v1/projects/[project-id]/databases/(default)/documents",
});
const userApi = createApi({
baseQuery: baseQuery,
reducerPath: "users",
endpoints: (builder) => ({
createUser: builder.mutation({
query: (userInfo: RegisterUser) => ({
url: `/users/${user.uid}`, //👈 Custom document ID.
method: "POST",
body: {
fields: {
email: { stringValue: userInfo.email },
fullname: { stringValue: userInfo.fullname },
trips: {
arrayValue: [],
},
},
},
}),
}),
So if you include a custom document ID in the URL, you tell Firestore to create a document with that specific ID instead of generating a random one.
7