AnswerBun.com

How to mutate complex object with nested array with SWR?

Stack Overflow Asked by GeraltDieSocke on January 13, 2021

TL;DR:

How can I spread a new object inside a nested array e.g. data.posts.votes and also keep all the existing state from data

Full Info:

I have data I fetch that looks like that:

enter image description here

I want to have an upvote functionality that adds a new vote object into the votes array in the screenshot above.

I really have no plan right now how to do this in the mutate function from swr:

Right now I have it like this but that won’t work:

mutate(
    `/api/subreddit/findSubreddit?name=${fullSub.name}`,
    (data) => {
      console.log(data);
      return {
        ...data,
        posts: (data.posts[postid].votes = [
          ...data.posts[postid].votes,
          { voteType: "UPVOTE" },
        ]),
      };
    },
    false
  );

How can I optimistically update this?

One Answer

I think your approach should be like this:

mutate(
  `/api/subreddit/findSubreddit?name=${fullSub.name}`,
  async (data) => {
    console.log(data);
    return {
      ...data,
      posts: data.posts.map((post) => {
        if (post.id === postid) {
          return {
            ...post,
            votes: [...post.votes, { voteType: "UPVOTE" }],
          };
        } else {
          return post;
        }
      }),
    };
  },
  false
);

Correct answer by Taghi Khavari on January 13, 2021

Add your own answers!

Related Questions

How to convet this data to array?(Typescript )

1  Asked on December 23, 2021 by pyarel

   

Why is the user defined time’s location nil

1  Asked on December 23, 2021 by kelly-flet

 

Can i uncheck radio button?

3  Asked on December 23, 2021 by frankfurt

     

Call this.Hide() but the Form is still activated on Win10

0  Asked on December 23, 2021 by jonney

 

How do you remotely update Java applications?

9  Asked on December 23, 2021 by david-crow

   

how to embed plot in gtk and glade

1  Asked on December 23, 2021 by user169808

     

Multivariate normal density in Python?

10  Asked on December 23, 2021 by benno

       

onBlur for div element in React

1  Asked on December 23, 2021 by neel-dsouza

   

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir