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?

4 Answers 4

2

You can do it like so..

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

this.setState({filters});
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

Note that you may also use the immutable.js library, which has methods specifically for these cases.
Thanks I got the solution, I worked with the following code this.setState({ filters:{ [field]:{ value:e } }
1

Check this out:

this.setState({filters:{[field]:{value:e}}

1 Comment

Answering questions is good, thank you. But giving an answer that is just code with no explanation is not very useful.
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

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.