How to mutate complex object with nested array with SWR?

Stack Overflow Asked by GeraltDieSocke on January 13, 2021


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:

    (data) => {
      return {,
        posts: (data.posts[postid].votes = [
          { voteType: "UPVOTE" },

How can I optimistically update this?

One Answer

I think your approach should be like this:

  async (data) => {
    return {,
      posts: => {
        if ( === postid) {
          return {
            votes: [, { voteType: "UPVOTE" }],
        } else {
          return post;

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 All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir