I am fetching data from jsonplaceholder. It works correctly. But I want to add new position to the list using RTK query. Request is being submitted successfully, but the new item is not being added to my list. What I am doing wrong?
That's my slice:
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
export const apiUsersSlice = createApi({
reducerPath: "apiUsersSlice",
baseQuery: fetchBaseQuery({
baseUrl: "https://my-json-server.typicode.com",
}),
tagTypes: ['Users'],
endpoints: (builder) => ({
getUsers: builder.query({
query: () => "/karolkproexe/jsonplaceholderdb/data",
providesTags: ['Users'],
transformResponse: (response) => {
const data = response.map((obj) => ({
id: obj.id,
name: obj.name,
username: obj.username,
city: obj.address.city,
email: obj.email,
}));
return data;
},
}),
addUser: builder.mutation({
query: (body) => ({
url: '/karolkproexe/jsonplaceholderdb/data',
method: 'POST',
body,
invalidatesTags: ['Users'],
}),
transformResponse: (response) => response.data,
}),
}),
});
export const { useGetUsersQuery, useAddUserMutation } = apiUsersSlice;
That's my store file:
import { configureStore } from "@reduxjs/toolkit"
import { apiUsersSlice } from "./api/apiUsersSlice";
export const store = configureStore({
reducer : {
[apiUsersSlice.reducerPath] : apiUsersSlice.reducer,
},
middleware : (getDefaultMiddlewares) =>
getDefaultMiddlewares().concat(apiUsersSlice.middleware),
})
And of course the index file:
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { Provider } from 'react-redux';
import { ApiProvider } from "@reduxjs/toolkit/dist/query/react";
import { apiUsersSlice } from "./api/apiUsersSlice";
import {store} from './store';
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
If it's not possible to add new item to the list because of fake json server, what can I do to solve my problem? I thought about saving data from rtk query to local storage and then to operate on it, but I found some answers that's not possible.
CodePudding user response:
Yeah, it's likely the use of jsonplaceholder
here that's the issue.
The normal RTK Query usage pattern is that you use a "mutation" request to send an update to the server, then have RTK Query automatically re-fetch the "query" data via matching tags.
However, jsonplaceholder
doesn't support actually updating data on the server. My understanding is that you can send a POST
or PUT
request and it will respond 200 OK
, but there's no actual update made - the data is all fixed and does not change. So, even if RTKQ does try to re-fetch the data, it gets the same query response as last time.
You'll need to have a more realistic server that your client app talks to in order to experiment with using mutations and actually updating data.