Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

251
Visualizações
useSWRInfinite with pagination and mutate features

I'm using useSWR to fetch data from client side in nextjs.

What I am doing and trying to achieve

I am using useSWRInfinite for the pagination feature and trying to update comments like state with bound mutate function with optimisticData option since I wanted to refresh the data immediately.(client-side perspective)

-> https://swr.vercel.app/docs/mutation#optimistic-updates and then get a new updated comment from axios and replace it with a previous comment that should be updated.

Expected

The data from useSWRInfinite should be updated right away since I am using optimisticData option until the API call is done and I could've set revalidate option to true but an async function in the mutate returns updated data with the response from axios. I didn't need it.

Actual behaviour

Even though I am passing optimisticData to the mutate, It doesn't update the data immediately. It keeps waiting until The API call is done and then gets updated.

What I've tried

I have tried using just normal useSWR function without the pagination feature and it worked well as I expected.

const { data, error, isValidating, mutate, size, setSize } = useSWRInfinite<CommentType[]>(
   (index) => `/api/comment?postId=${postId}&currentPage=${index + 1}`,
   fetcher,
   { revalidateFirstPage: false }
);

  const likeCommentHandler = async (commentId: string, dislike: boolean) => {
    const optimisticData = data?.map((comments) => {
      return comments.map((comment) => {
        if (comment.id === commentId) {
          if (dislike) {
            --comment._count.likedBy;
            comment.likedByIds = comment.likedByIds.filter(
              (likeById) => likeById !== session!.user.id
            );
          } else {
            comment.likedByIds.push(session!.user.id);
            ++comment._count.likedBy;
          }
          return { ...comment };
        } else {
          return { ...comment };
        }
      });
    });

    mutate(
      async (data) => {
        const { data: result } = await axios.post("/api/likeComment", {
          commentId: commentId,
          userId: session?.user.id,
          dislike,
        });

        const newData = data?.map((comments) => {
          return comments.map((comment) => {
            if (comment.id === result.comment.id) {
              return result.comment;
            } else {
              return comment;
            }
          });
        });

        return newData;
      },
      { optimisticData, revalidate: false, populateCache: true }
    );
  };
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda