Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

246
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda