0

Today i tried to change values inside a array using state. So i have a simple array like -

  const [data, setData] = React.useState([
    {
      label: "data 1",
    },
    {
      label: "data 2",
    },
  ]);

Also i dont know is it good idea to use array in state. I created a button and text component also.

<View style={{ justifyContent: "flex-start", top: 50 }}>
  <Button
    title={"test"}
    onPress={() => {
      data[0].label = "fdsfsd";
      setData(data);
    }}
  />
  <Text>{data[0].label}</Text>
</View>

So my idea is when i click button to change data[0].label. But unfortunately it is not change? Why?

Hristo Ivanov
  • 405
  • 1
  • 3
  • 7
  • https://stackoverflow.com/questions/37755997/why-cant-i-directly-modify-a-components-state-really – ksav Sep 18 '21 at 09:45
  • Does this answer your question? [Why can't I directly modify a component's state, really?](https://stackoverflow.com/questions/37755997/why-cant-i-directly-modify-a-components-state-really) – Shivam Sep 18 '21 at 10:16

2 Answers2

2

Change your onPress to this

onPress={() => {
  let temp = [...data];
  temp[0].label = 'asdasdasdasd';
  setData(temp);
}}

Working Example here

Read More about State Updates, Immutable Approaches etc here - https://www.freecodecamp.org/news/handling-state-in-react-four-immutable-approaches-to-consider-d1f5c00249d5/

Kartikey
  • 4,516
  • 4
  • 15
  • 40
0

You can try this, it will work

<View style={{ justifyContent: "flex-start", top: 50 }}>
  <Button
    title={"test"}
    onPress={() => {
      data[0].label = "fdsfsd";
    }}
  />
  <Text>{data[0].label}</Text>
</View>
Shivam
  • 2,147
  • 1
  • 11
  • 28