Home > front end >  Spreading array to set a new state
Spreading array to set a new state

Time:12-25

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?

CodePudding user response:

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.

  • Related