1

Remove item from array work only on last item rendered but item selected deleted from list

  const [otherPhones, setOtherPhones] = useState([]);

    {otherPhones.map((item, i) => {
      return (
        <View
          style={{
            ...DefaultStyles.iconContainer,
            marginBottom: hp("1.25%")
          }}
          key={i}
        >
          <PhoneNumberPicker
            placeholder={i18n.t("other_phone")}
            style={{ flex: 10 }}
            countryHint={countryHint}
            onChange={value => {
              _handleOtherPhone(value, i);
            }}
          />
          <IconButton
            style={{ flex: 1 }}
            icon="trash-can-outline"
            color={SECONDARY}
            size={SCALE_20}
            onPress={_deleteOtherPhone.bind(this, i)}
          />
        </View>
      );
    })}

  const _deleteOtherPhone = index => {
    const temp = [...otherPhones];
    temp.splice(index, 1);
    setOtherPhones(temp);
  };

When i delete PhoneNumberPicker and display only simple property item everything work fine. PhoneNumberPicker it's a TextInput with some additional component.

2
  • what about using a filter instead of splice? have you tried? Commented May 22, 2020 at 22:57
  • Yeah yeah for sure i try it too, the element was removed from the array on both cases but the Child component not updated correctly. Thanks for your response by the way. Commented May 22, 2020 at 23:11

1 Answer 1

1

Maybe this will help someone, i use useRef() react hooks to refer for every rendered Child on the DOM then i use to update them (after deleting selected element) with the new index after removing an item.

Parent element :

 const elRefs = useRef([]);
 if (elRefs.current.length !== otherPhones.length) {
    // add or remove refs
    elRefs.current = Array(otherPhones.length)
      .fill()
      .map((_, i) => elRefs.current[i] || createRef());
  }

...

  const _deleteOtherPhone = index => {
  const temp = [...otherPhones];
  temp.splice(index, 1);
  for (let i = 0; i < temp.length; i++) {
      const element = temp[i];
      elRefs.current[i].current.removeItem(element);
  }
...
}

...
    <PhoneNumberPicker
    placeholder={i18n.t("other_phone")}
    style={{ flex: 10 }}
    ref={elRefs.current[i]}
    countryHint={countryHint}
    onChange={value => {
    _handleOtherPhone(value, i);
     }}
   />
...

Child element PhoneNumberPicker : update phone number :

  removeItem(item) {
    this.setState({ phoneNo: item.phoneNumber });
  }
Sign up to request clarification or add additional context in comments.

Comments

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.