This RTkQuery endpoint is meant to create a post in Firestore. It takes two parameters, post and file. , and uses the addDoc() and updateDoc() functions to create the post in Firestore. It then checks if a file was provided, and if so, it meant to upload the file to storage using the uploadString() function. Finally, it gets the download URL for the file using getDownloadURL() and updates the post with this URL. The mutation also invalidates any cached Post data.
createPost: builder.mutation({
queryFn: async(post: Post, file?: string) => {
try {
const postRef = await addDoc(collection(firestore, 'posts'), post);
await updateDoc(postRef, { id: postRef.id });
if (file) {
const imageRef = ref(storage, `posts/${postRef.id}/image`);
await uploadString(imageRef, file, 'data_url');
const imageUrl = await getDownloadURL(imageRef);
await updateDoc(postRef, { imageUrl });
}
console.log('imageUrl: ', post.imageUrl);
return { data: { postRef } };
} catch (error: any) {
return { error: error.message };
}
},
invalidatesTags: ['Post']
}),
But when it's called on the front end I've got this instead
Expected 1 arguments, but got 2.ts(2554)
// imports
import { useCreatePostMutation } from '@/features/api/apiSlice';
// hook call
const [ createPost, { data } ] = useCreatePostMutation();
const handleCreatePost = async() => {
const { community } = router.query;
const { title, text } = form;
const newPost: Post = {
communityName: community as string,
authorId: user.uid,
authorUsername: user.email?.split('@')[0] || 'Anonymous',
title,
text,
active: false,
numberOfComments: 0,
numberOfUpvotes: 0,
createdAt: serverTimestamp(),
}
try {
await createPost(newPost, file);
} catch (error) {
console.log({error});
}
router.back();
}
I would appreciate any light thrown to guide me out this dark dead-end.
The hook trigger function only allows for one argument, and will also only pass one argument to your queryFn
. So use an object for that:
createPost: builder.mutation({
queryFn: async({post, file}: {post: Post, file?: string}) => {
and
await createPost({ post: newPost, file });