2

I'm trying to add/push a javascript object (let's call this 'session') to this.state.sessions.

I've tried this two ways:
1) Concat'ing the new session

this.setState({sessions: this.state.sessions.concat(session)});

2) Using React's immutability helpers

var newState = React.addons.update(this.state, {
            sessions : {
                $push : [session]
            }
        });
this.setState(newState);

While the shallow data (e.g. sessions[i].location) is added correctly, the problem is that all prior session's scope is now set to the new session.scope. In the picture link below you can see that the first session's scope values (sessions[0].scope) were overwritten by the second session's scope values (sessions[1].scope). How do I ensure that when I add a new session, prior session's values aren't affected?

App state picture

2 Answers 2

1

I think this has little to do with react, and the problem might be that the object in sessions[0].scope is copied by reference. That scope object might be reference shared between the old and new session values.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm marking this as the answer. Although I haven't solved the problem on my original codebase, I created a simpler app (still with child components) and scope updates as expected.
1

Since sessions is an array, I would've done the following:

addSession = (newSession) => {
  let tempArray = this.state.sessions.slice();
  tempArray.push(newSession);
  this.setState({sessions: tempArray});
}

The above creates a shallow copy of the sessions array and puts it in a temporary variable. Next, it pushes the new session into the array and once that's done we overwrite the this.state.sessions with the new variable.

1 Comment

Thanks Chris, I gave your suggestion a go but alas the same issue persisted but I noted the following oddity: I set a breakpoint after let tempArray = this.state.sessions.slice();. I added two sessions, one without scope sessions[0].scope = [] and one with scope sessions[1].scope = [{id: 1, ...}]. What's strange is that tempArray already has applied the second session's scope to the first sessions scope i.e. `session[0].scope==session[1].scope.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.