I'm using RTK Query to get the user logged and put in my app, like showing user logged in header, etc. But, when i logged for first time, it shows only the old token, when i refresh the page, it shows the actual token and data.
My RTK Query archive looks like that:
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
const useAuthToken = () => {
const token = localStorage.getItem("token");
return token ? `Bearer ${token}` : null;
};
export const usersApi = createApi({
reducerPath: "users",
baseQuery: fetchBaseQuery({
baseUrl: "http://127.0.0.1:8080",
headers: {
Authorization: useAuthToken(),
},
}),
endpoints: (builder) => ({
getUserLogged: builder.query({
query: () => "/check/token",
}),
}),
}),
});
export const {
useGetUserLoggedQuery,
} = usersApi;
and in other pages i get the info:
const { data, error, isLoading } = useGetUserLoggedQuery();
const [dataResults, setDataResults] = useState([]);
useEffect(() => {
if (data) {
setDataResults(data);
} else if (isLoading) {
console.log("loading");
} else if (error) {
console.log(error);
}
}
}, [data]);
and show to the user...
all works fine untill i logout and log in again, it shows the old data using the old token, but if i refresh the page, it works normally.
i know that it getting the old token in RTK QUERY fetching, but how i can deal with that everytime i logout?
I know that's is old, but this is the answer at the time that it works:
first import your createApi function name:
import {
usersApi,
} from "../components/store/service/UsersData";
and after that call this after login(or wherever you want):
usersApi.util.resetApiState()