3

I am trying to create an object in state in React .What I require us that 'status' is actually a field that is updated by setState

 this.state = {
        data:[],
        sort: 0,
        field:"",
        filters:{
            'status':{
                value:""
            }

The code should be:

this.state = {
        data:[],
        sort: 0,
        field:"",
        filters:{
            field:{
                value:""
            }

How should I set the same object to the nested object?

beingshuchi
  • 109
  • 1
  • 10

4 Answers4

2

You can do it like so..

let filters = {
  field:{
    value: ""
  }
};

this.setState({filters});
lloydaf
  • 605
  • 3
  • 17
2

You can do it this way:

this.setState({
  filters: { ...this.state.filters, field: { value: 'new value' },
});

However the above syntax is ugly. I recommend you to use immutability-helper package to update the state.

See this answer on how to update state with immutability helper.

JeanAlesi
  • 478
  • 3
  • 17
  • Note that you may also use the [immutable.js](https://facebook.github.io/immutable-js/) library, which has methods specifically for these cases. – JeanAlesi Nov 30 '18 at 04:35
  • Thanks I got the solution, I worked with the following code this.setState({ filters:{ [field]:{ value:e } } – beingshuchi Nov 30 '18 at 10:32
1

Check this out:

this.setState({filters:{[field]:{value:e}}
zx485
  • 28,498
  • 28
  • 50
  • 59
Eshita
  • 26
  • 2
  • 1
    Answering questions is good, thank you. But giving an answer that is just code with no explanation is not very useful. – AdrianHHH Jan 21 '19 at 18:29
0

setState for nested object.

 this.state = {
        data:[],
        sort: 0,
        field:"",
        filters:{
            status:{
                value:""
            }

If we want update 'status' using setState method follow this method this may help you.

let filters = {...this.state.filters}
filters.status = { value: 10 };
this.setState({filters})

Ref this doc: Link

EDISON J
  • 324
  • 3
  • 12