0

I am trying to set the state for an object like this

vault:{
    main:{
        a:1,
        b:2,
        c:3
    },
    backup:{
        d:4,
        e:5,
        f:6
    }
}

when I this.setState({vault:{main:{a:10}}} it deletes all other entries,

I tried using the "underscore library" with the "extend"

How do I get around setting the state of part of a library? seems very strange that this is not possible...

ELI7VH
  • 504
  • 1
  • 5
  • 12

3 Answers3

1

What about this?

this.setState({
    vault:{
        ...this.state.vault,
        main:{
            ...this.state.vault.main,
            a:10
        }
    }
})
0

Use Object.assign

let newstate = Object.assign({}, this.state);
newstate.main.a = 10;
this.setState({vault:newstate});

OR

vault:{
    main:{
        a:1,
        b:2,
        c:3
    },
    backup:{
        d:4,
        e:5,
        f:6
    }
}
var new_state = vault;
new_state.main.a =10;
this.setState({vault:new_state}); 

var vault = {
    main:{
        a:1,
        b:2,
        c:3
    },
    backup:{
        d:4,
        e:5,
        f:6
    }
};

let newstate = Object.assign({}, vault);

newstate.main.a = 10;
console.log(newstate);


var new_state = vault;
new_state.main.a =10;
console.log(newstate);
Dinesh undefined
  • 5,490
  • 2
  • 19
  • 40
  • Thank you for this ! So I actually managed to update the object using the simple second option.. i don't know why I couldn't find a reference to this before.... I swear I looked at about 20 different pages. One thing, it updates my state object, but then when i reference my object to populate my site, it gives me bugs. for example when I type "440" in the input, I get "4" in my {this.state.vault.main.a} – ELI7VH Jun 11 '17 at 04:19
0

In addition to @Dinesh answer,

You cannot update the nested state directly, you need to create a new object, reset it and then update it back to state.

If you are using ES6 script for your React project, you can make use of spread operator to update the state

Assuming

state = {

    vault:{
        main:{
            a:1,
            b:2,
            c:3
        },
        backup:{
            d:4,
            e:5,
            f:6
        }
    }
}

you can update the state like

var vault = {...this.state.vault}
vault.main.a = 10
this.setState({vault})

To know what spread operator does, read this DOCS and this answer

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • When you say , you type 440 in input and you see 4, how are you passing the input to the function where you are updating state – Shubham Khatri Jun 11 '17 at 06:58