0

I am trying to rename [0]items in FlatList by clicking some item, But it doesn't work for me, when i click on each item nothing happen and i don't get any error. How can i fix this?

This is my code.

export default function renameSample() {

  const data = [
    {
      id: '1',
      name: 'test1',
    },
    {
      id: '2',
      name: 'test2',
    },
    {
      id: '3',
      name: 'test3',
    },
  ];
  
  const [stateUser, onChangeUser] = useState(data);

  return (
      <FlatList
        data={stateUser}
        renderItem={({item}) =>
          <TouchableOpacity
            onPress={() => {
              let setData = stateUser;
              setData[0].name = 'changed';
              onChangeUser(setData);
            }
            }
          >
            <Item name={item.name} />
          </TouchableOpacity>
        }
        keyExtractor={item => item.id}
      />
    </View>
  );
}

2
  • Can you share it on snack Commented Jul 12, 2020 at 9:32
  • 1
    should this be stateUser or selectUser? let setData = selectUser; Commented Jul 12, 2020 at 9:35

1 Answer 1

0

If your requirement is to change the clicked item, the code would be like below. You can get the index of the clicked item and change it.

function RenameSample() {
  const data = [
    {
      id: '1',
      name: 'test1',
    },
    {
      id: '2',
      name: 'test2',
    },
    {
      id: '3',
      name: 'test3',
    },
  ];

  const [stateUser, onChangeUser] = useState(data);

  return (
    <View>
      <FlatList
        data={stateUser}
        renderItem={({ item, index }) => (
          <TouchableOpacity
            onPress={() => {
             const newData=[...stateUser];
             newData[index].name = 'changed';
             onChangeUser(newData);
            }}>
            <Item name={item.name} />
          </TouchableOpacity>
        )}
        keyExtractor={(item) => item.id}
      />
    </View>
  );
}
Sign up to request clarification or add additional context in comments.

4 Comments

Are not you mutating a state directly here? stateUser[index].name = 'changed';
Thanks, it’s working!!!! I really appreciate your help.
@Zen_Web updated the code, i wasnt sure whether thats a different item selectUser so came up with a code
I fixed "onChangeUser(setData);" to "onChangeUser([...setData]);", then it’s working. Thank you for everyone involved.

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.