0

I have a unique situation that I'm struggling with. I have some data like this. Excuse any incorrect terms as I'm fairly new to this.

usersByName: {
    "tester": {
        0: {
            id: 123
            name: "Some Name"
            data: "Some data"
        },
        1: {
            id: 124
            name: "Some Name 2"
            data: "Some data 2"
        },
        2: {
            id: 125
            name: "Some Name 3"
            data: "Some data 4"
        },
    },
    "tester 2": {
        0: {
            id: 12
            name: "Some Name"
            data: "Some data"
        },
        1: {
            id: 13
            name: "Some Name 2"
            data: "Some data 2"
        },
    }
 }

I am returning a piece of data like this.

 {
      id: 44
      name: "Some Name New"
      data: "Some data New"
 }

and a name like tester 2.

How can I add the new piece of data to the name I have found so the new data gets added as a third element to tester 2. I am using react and next js so hoping to add it directly to the state if possible. I think something like this but can't work out the obvious parts of it that are wrong

this.setState((prevState) => ({
  usersByName: { // copy all other key-value pairs
    newuservar: {
      ...prevState.usersByName.newuservar, // copy all pizza key-value pairs
      X: newData,
    },
  },
}))

1 Answer 1

2

Since I see the user objects have the key start with numbers, I assume they're arrays. Try this:

// newuservar = 'tester 2';
this.setState((prevState) => ({
  usersByName: {
    ...prevState.usersByName,
    [newuservar]: prevState.usersByName[newuservar].concat(newData)
  },
}))
Sign up to request clarification or add additional context in comments.

Comments

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.