0

I am using the following approach to dynamically update the state using map. However this does not work and the state does not change. Why is this approach invalid and what should be the alternative?

    values= ['test1', 'test2','test3'] // The array could contain anything 
    this.setState({
          events: [
            ...events,
            values.map((value) => {
              return {
                title: value,
                start: this.state.start,
                end: this.state.end,
              };
            }),
          ],
        });

1 Answer 1

1

I might be wrong, but to me it looks like you're only missing a spread operator in front of values.map(...)

this.setState({
          events: [
            ...events,
            ...values.map((value) => {
              return {
                title: value,
                start: this.state.start,
                end: this.state.end,
              };
            }),
          ],
        });

Because values.map(...) returns an array, and seeing that you spread events, I'm guessing you want the mapped values to be spread as well. If I'm misunderstanding something, please let me know and we can look into it further.

Also, unless you destructured events from state earlier (in code you did not paste here), you might want to refer to it as this.state.events.


Edit:

A more detailed explanation about why the spread operator was the solution:

In your state the property events is an array of objects. So when you change it's value, it must again be an array of objects.

Perhaps the most important details is that values.map returns an array.

events is an array of objects. The same is true for values.map.

So [events, values.map] would be an array with two arrays, one in positions 0 and the other in position 1.

But you want an array of objects, not an array of arrays. Therefore, you must spread both of them.

I hope it's clearer now. If you have any more questions, please feel free to ask.

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

2 Comments

Yes your solution worked. Can you please explain a bit more why we had to use spread operator with the map function? Didn't get the logic well
Of course! I've edited my main post with a more detailed explanation, since I can't really format in 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.