0

I have the following structure of the state:

this.state = {
    data: {
        tags: []
    },
    items: [],
    input: ''
 };

When I submit the data, I am trying to assign the tags array with the items array data.

var newData = this.state.items.slice(); //copy array
this.setState({
    ...this.state,
    data: { ...this.state.data, tags: newData }
});

The newData has all variables inside, but tags is always empty. How can I assign exactly the same values into the tags array?

Here is my console log:

console.log(this.state.data.tags, this.state.items);

enter image description here

UPDATE:

onSubmit = (e) => {
     e.preventDefault();
     const errors = this.validate(this.state.data);
     this.setState({ errors });
     if (Object.keys(errors).length === 0) {
       this.setState({ loading: true });
       this.setState(prevState => ({
          data: {
             ...prevState.data,
             tags: prevState.items
           }
       }));
       console.log(this.state.data.tags, this.state.items);
       this.props
         .submit(this.state.data)
         .catch(err =>
            this.setState({ errors: err.response.data.errors, loading: false })
          );
       }
   };

1 Answer 1

2

When you set state, you don't spread the current state into the object you're passing. setState takes in an object as it's first argument and only updates the keys in that object. So, for example if we had:

this.state = {
  a: 1,
  b: 2
};

Using this:

this.setState({
  b: 3
});

Will only update b. a will not be affected. Also, note that setState is asynchronous - and it's not guaranteed safe to reference state inside setState. Thus, React provides you with a callback to access the previous state:

this.setState(prevState => ({
  data: { 
    ...prevState.data, 
    tags: prevState.items
  } 
}));

This will only update the data object in state, and only the tag property, with the previous state's items array.

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

6 Comments

Thank you for your explanation. However, after using this method, array of tags is still empty
@Julia are you sure items is not empty?
yes, also I updated my post to show you my console log. I just found the strange problem that the array inside this.state.data is harder to change comparing with this.state . could be some problem with that?
you mean I am setting it in the wrong place? I will update my answer in a few seconds
@Julia With your code, my answer should work. There's no way this.state.items changes between those two calls
|

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.