V
V
vovashaplin2020-11-26 01:48:16
React
vovashaplin, 2020-11-26 01:48:16

How is it that useSWR produces an object when an array should?

I have useSWR and put data from SSR into it as initial and get an array. If it is stupid to console the data with SSR, then they regularly give out normal information.

The problem is that useSWR sometimes miraculously returns an OBJECT to me, or even becomes an empty array during the second log console. Sir, how is this possible?

And the most amazing 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 similar there). But on the page where IT happened there were 3 of these requests. I've been racking my brains for a long time, I think it's magic. I'm inclined to believe that the backender is to blame, but he denies it.

Here is the component:

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>
  );
};


Here is the SSR part from which chats come:
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,
    },
  };
};


Here are the global settings:
<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),
          }}
        >
.......

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question