redux-toolkit
redux-toolkit copied to clipboard
Mutation queries does not work as expected
I have a mutation query in a page in my reactjs project. I work properly and update user's profile in the main page. I navigate to other page and navigate back to the main page with useNavigate from react-router-dom. Now if I try to update user's profile again, everything works fine in the network tab of my browser, but result of calling update hooks remains in pending status and no result come back to the browser properly. I think this is an issue and should be fixed. Please let me know if you think like me and guide me to solve this problem.
Best regards.
define api hooks like this
const myBaseQuery = fetchBaseQuery({
baseUrl: import.meta.env.VITE_EMDADGAR_EXPERT_URL,
prepareHeaders: (headers, { getState }) => {
const token = getCookie(expertTokenName)
if (token) {
headers.set('authorization', `Bearer ${token}`)
}
headers.set('Accept', 'application/json')
// headers.set('Content-Type', 'application/json')
return headers
},
});
const baseQueryWith401Handling: BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}> = async (
args,
api,
extraOptions
) => {
let result = await myBaseQuery(args, api, extraOptions)
if (result.error && result.error.status === 401) {
clearCookie(expertTokenName)
// localStorage.removeItem(expertTokenName)
window.location.replace("/expert/login")
}
if (result.error && +result.error.status >= 500) {
// window.location.replace("/500")
}
if (result.error && +result.error.status === 403) {
// window.location.replace("/403")
}
return result
};
export const api = createApi({
reducerPath: 'api',
baseQuery: baseQueryWith401Handling,
tagTypes: ['Profile'],
endpoints(builder) {
return {
expertUpdate: builder.mutation<ExpertProfile, { first_name?: string, last_name?: string, national_code?: string, iban?: string, ready_to_service?: number, notification_key?: string, profile_image?: string, rescue_vehicle_id?: string, vehicle_plate?: string, service_type_ids?: number[] }>({
query: ({ first_name, last_name, national_code, iban, ready_to_service, notification_key, profile_image, rescue_vehicle_id, vehicle_plate, service_type_ids }) => ({
url: `/expert/profile`,
method: 'PUT',
body: { first_name, last_name, national_code, iban, ready_to_service, notification_key, profile_image, rescue_vehicle_id, vehicle_plate, service_type_ids }
}),
invalidatesTags: ['Profile'],
}),
}
}
})
export const {
useExpertUpdateMutation,
} = api
a part of my component which calls hook api
import { useEffect } from "react";
import { useExpertUpdateMutation } from "@store/expert/slices/api";
export const ExpertBottomNavigation = () => {
const [updateExpertTrigger, updateExpertResult] = useExpertUpdateMutation();
useEffect(() => {
if(updateExpertResult.isSuccess) {
console.log(updateExpertResult)
}
}, [updateExpertResult.isSuccess])
return (
<button onClick={() => updateExpertTrigger({ready_to_service: 0})}>
Update
</button>
);
};