Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Spreading array to set a new state

I am working in React.JS and trying to set a new state by spreading array of objects and changing a value of one of them. I have an array of objects with key and another object as a value. Like this:

    [
        {"first": {
            "backlog":[...]
            }
        }, 
        {"second": {
            "backlog":[...]
            }
        },
        {"third": {
            "backlog":[...]
            }
        }
    ]

I also have variable selected with one of object’s key as a value. So I want to spread my entire array as a new state, but with a slight change to a backlog of exact object. The key of it’s object is saved in selected variable. The problem is, I can’t reach it the object I need. I tried to do it like this, but I understand where I was wrong:

setProjects((prevProjects) => 
            ([...prevProjects, [selected]: {...prevProjects[selected], backlog: [...prevProjects[selected].backlog, NewObj ]}])
        )

Is it even possible to achieve? If yes, how?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You will have to find the index of the object with the key in the outer array, and then update that index while mapping over the state.

const index = projects.findIndex(obj => obj[selected]);
setProjects(
  projects.map((project, i) => (
    i === index
      ? { backlog: [...project.backlog, NewObj] }
      : project
  ))
);

But consider if you could use an easier data structure to make manipulations of it easier.

const [projects, setProjects] = useState({
  first: [...], // first backlog
  second: [...], // second backlog
  // etc
});

Then you can update with

setProjects({
  ...projects,
  [selected]: [...projects[selected], NewObj]
});

You don’t need to use the callback form (setProjects((prevProjects) =>) unless you’ve previously updated the projects state synchronously and the component hasn’t re-rendered yet. Sometimes it’s necessary, but usually it isn’t.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading