I’m trying to display private user data after they log in. However, upon logging in, I receive an error in the console:
GET http://localhost:8000/api/v1/chat 401 (Unauthorized)
The data is only displayed after I manually refresh the browser.
Here’s my code for the Sidebar
component:
const Sidebar = () => {
const { data, isLoading } = useGetChatQuery();
console.log(useGetChatQuery()); // -> `status: 'pending'`, and then `status: 'rejected'` -> but after manually refreshing, `status: 'fulfilled'`
console.log(data); // -> "Bad Token" (as I set it in the backend for wrong tokens) -> after manually refreshing: "Some data"
if (!data || isLoading) return <div>is loading</div>; // so it keeps showing this until I refresh, then it shows "Something" below.
return <div id="sidebar-mid">Something</div>;
};
And here’s my apiChat
RTK query file:
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import Userfront from "@userfront/react";
export const apiChat = createApi({
reducerPath: "apiChat",
baseQuery: fetchBaseQuery({
baseUrl: process.env.REACT_APP_BASE_URL,
}),
tagTypes: ["getChat"],
endpoints: (build) => ({
getChat: build.query({
query(args) {
return {
url: `/api/v1/chat`,
headers: {
Authorization: `Bearer ${Userfront.accessToken()}`,
},
};
},
providesTags: ["getChat"],
}),
}),
});
export const { useGetChatQuery } = apiChat;
Any advice on how to resolve this issue would be greatly appreciated. Thank you!