How to make useSWR mutations with a given initial value?

6.1k Views Asked by At

The problem is that if I remove the initial value then everything works. I think that data with initial values is not cached. But I don't know how to solve this. In case with initial data mutate return undefinded.

In page component:

  const { data, error } = useSWR("/api/company/", {
    initialData: company,
  });
export const getServerSideProps: GetServerSideProps<IManage> = async (ctx) => {
  ensureAuth(ctx);
  let company: ICompany[] | null = null;
  await instanceWithSSR(ctx) // axios config
    .get(`/api/company/`)
    .then((response) => {
      company = response?.data;
    })
    .catch((error) => {
      console.log(error);
    });
  return {
    props: {
      company: company || null,
    },
  };
};

My mutation:

  mutate(url, async (company: ICompany[]) => {
    console.log(company)
    if (company) {
      return [...company, companyItem];
    }
  }, false);
2

There are 2 best solutions below

1
On BEST ANSWER

I'm not sure about your payload for company, but with initial values, it's not revalidated when mount so u need to set revalidateOnMount to true.

 const { data, error, mutate } = useSWR("/api/company/", {
    initialData: company,
    revalidateOnMount: true
  });

useSWR also provides a locate mutate so u don't need to provide the url in same component.

mutate(async(prev) => [...prev, companyItem])
0
On

I am using swr 1.2.2 version. Looks like after version 1.0 initialData is no longer exists. It replaced with fallbackData