Reputation: 1786
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 ?
Upvotes: 2
Views: 1624
Reputation: 7819
At this level of nesting I suggest you to use the immer library:
import produce from "immer"
this.setState((oldState) => {
return produce(oldState, draftState => {
draftState.Pages.Langs.push({ lang: 'it_IT', text: 'foo' })
})
})
The power of immer is that you can modify the draft as you want, without touching the old state.
Upvotes: 2
Reputation: 112787
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 };
});
};
Upvotes: 4