I
I
ivan_ivanov_ivanych2021-02-06 00:38:22
JavaScript
ivan_ivanov_ivanych, 2021-02-06 00:38:22

How to update nested array in React?

Good day!
I need to change the state of an element nested in an array, namely questions_count:

this.state = {
      data: [],
      isLoaded: false,
      content: {
        exams:[],
        subjects: [],
        numbers: [],
        themes: [
          {
            id: 16, 
            questions_count: 8, 
            title: "Квадратные ура…"
          },
          {
            id: 14, 
            questions_count: 2, 
            title: "Арифметическая…"
          },
          {
            id: 15, 
            questions_count: 2, 
            title: "Геометрическая…"
          }
        ]
   }

This method gives a compilation error:
this.setState({
    content.themes[i].questions_count: content.themes[i].questions_count++
 })

I also tried this method, but it also gives an error does not read with square brackets inside setState:
this.setState({
  ...this.state, content: {
      ...this.state.content, themes[i]: {
              ...this.state.content.themes[i], questions_count: questions_count++
              }
       }
 })

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Daniil Vasilyev, 2021-02-06
@ivan_ivanov_ivanych

Unfortunately, you will have to completely copy the content object with the new data in the array.

const newContent = { ...this.state.content };
newContent.themes[0].questions_count++;
this.setState({ content: newContent });

You can also divide everything by components, so it will be easier to control the state and, for example, collect it somewhere through events (callbacks in props), if necessary. And here, as an option, you can use Redux and from there separately pull an array with questions.

V
Vladimir, 2021-02-06
@Casufi

no need to keep such a complex object in a state, break it into objects with one level of nesting

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question