I have useSWR and I put data with SSR into it as an initial and get an array. If I make a console log of chats from SSR, then they regularly display normal information.
The problem is that useSWR sometimes miraculously returns an OBJECT to me or even becomes an empty array during the second console log. How is this possible?
And the most surprising thing is that a similar scheme works on other pages where there is only 1 useSWR request (if necessary, I can prove it with screenshots or code, it's the same there). But on the page where THIS happened these requests 3. I've been puzzling for a long time, I think this is magic. I am inclined to believe that the backender is to blame, but he denies it.
const ChatList: React.FC<IChatList> = ({ chats }) => {
const { data, error } = useSWR("/api/chat/", {
initialData: chats,
});
console.log(data);
if (error) return <ErrorMessage message="Ошибка загрузки чатов..." />;
if (!data) return <LoadingSpinner />;
if (data.length === 0)
return <EmptyMessage message="У вас пока нет чатов..." />;
return (
<SChatList>
{data.map((item, key) => {
return (
<ChatListItem
key={`chat__key__${item.user_name}__${key}`}
id={item.id}
userName={item.user_name}
isNotify={false}
isRead={item.is_read}
/>
);
})}
</SChatList>
);
};
Get chats from SSR:
export const getServerSideProps: GetServerSideProps<ISupport> = async (ctx) => {
let chats: IChat[] | null = null;
await instanceWithSSR(ctx)
.get("/api/chat/")
.then((response) => {
chats = response?.data;
})
.catch((error) => {
console.log(error);
});
return {
props: {
chats: chats || null,
},
};
};
Global useSWR config:
<SWRConfig
value={{
revalidateOnMount: true,
revalidateOnFocus: false,
dedupingInterval: 5000,
fetcher: (url) =>
axios({
url: url,
baseURL: process.env.DB_HOST,
headers: {
"Content-Type": "application/json",
Authorization: `Token ${Cookie.get("token")}`,
},
}).then((r) => r.data),
}}
>
.......