Next.js Discord

Discord Forum

Issue with SWR mutate when the key changes

Unanswered
Transvaal lion posted this in #help-forum
Open in Discord
Transvaal lionOP
Hello, I have a paginated table which uses data from a useSWR hook. There is a like button on every row that sends a request and when it comes back - updates the data locally with a bound mutate().
But when the user clicks the like button and then goes to page 2, when the like request returns and the mutate runs it overrides page 2 data with updated page 1 data. The only fix I came up with so far is to compare the params in the like button's function when the request returns, but that feels hacky. Is there a better way to do this? The hook looks like this:
export default function usePaginatedProcurements(
  params: GetProcurementsFilterParams,
) {
  const { data, error, isLoading, isValidating, mutate } = useSWR(
    ['procurementsPage', params],
    async () => {
      const { error, data } = await getProcurements(params)
      if (!data) {
        throw error
      }
      return data
    },
    {
      keepPreviousData: true,
    },
  )
  const procurementsPage = data || getEmptyLaravelPage<Procurement>()

  async function mutateProcurement(procurement: Procurement) {
    const updatedData = produce(procurementsPage, (draft) => {
      const index = draft.data.findIndex((p) => p.id === procurement.id)
      if (index !== -1) {
        draft.data[index] = procurement
      }
    })
    await mutate(updatedData, {
      revalidate: false,
    })
  }

  return {
    procurementsPage,
    procurementsError: error,
    loadingProcurements: isLoading,
    validatingProcurements: isValidating,
    mutateProcurement,
    mutateProcurements: mutate,
  }
}

0 Replies