Search code examples
arraysreactjsobjectstatesetstate

How to set a state of an array of object inside an array of objects in react


I'm trying to set a state inside an array of object inside another array of object. I tried a lot of things but i can't find the good solution.

Here's my array:

this.state = {
  Pages: [
    {
      image: undefined,
      audio: undefined,
      audioName: undefined,
      subtitles: 'up',
      Langs: [
        {
          lang: 'fr_FR',
          text: '',
        }
      ]
    }
  ]
};

I'm want to modify this.state.Pages[i].Langs[y].lang or .text value. Does some have an idea ?


Solution

  • You can create a copy of the Pages and Pages[i].Langs arrays, and create a copy of the Pages[i].Langs[y] object and overwrite the lang or text property.

    Example

    changeText = (i, y, text) => {
      this.setState(previousState => {
        const Pages = [...previousState.Pages];
        const Langs = [...Pages[i].Langs];
    
        Langs[y] = { ...Langs[y], text };
        Pages[i] = { ...Pages[i], Langs };
    
        return { Pages };
      });
    };