I am trying to fetch some data with RTK. GET method works properly. POST method also works but does not mutate data. I added provideTags and invalidateTags also for automatic refetch but still could not make it.
this is my store
import { configureStore } from "@reduxjs/toolkit";
import { verdeApiSlice } from "../features/verde/verde-slice";
export const store = configureStore({
reducer: {
[verdeApiSlice.reducerPath]: verdeApiSlice.reducer,
},
middleware: (getDefaultMiddleware) => {
return getDefaultMiddleware().concat(verdeApiSlice.middleware);
},
});
export const AppDispatch = store.dispatch;
export const RootState = store.getState;
this is slice
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
export const verdeApiSlice = createApi({
reducerPath: "verdeApi",
baseQuery: fetchBaseQuery({
baseUrl: "https://jsonplaceholder.typicode.com",
}),
tagTypes: ["Post"],
endpoints(builder) {
return {
getPosts: builder.query({
query: () => "/posts",
providesTags: ["Post"],
}),
addPost: builder.mutation({
query: (post) => ({
url: `/posts`,
method: "POST",
body: post,
}),
invalidatesTags: ["Post"],
}),
};
},
});
export const {
useGetPostsQuery,
useAddPostMutation,
} = verdeApiSlice;
export default verdeSlice.reducer;
And that is how i call addPost method
const [addPost, { isLoading }] = useAddPostMutation();
const handleClick = async (e) => {
e.preventDefault();
try {
await addPost(post).unwrap();
setPost(initialValue);
} catch (error) {
console.log("error", error);
}
};