Home > OS >  useState is not updating even after the value that trigger the update changes React Native
useState is not updating even after the value that trigger the update changes React Native

Time:06-27

I am trying to append object into Firestore. The method of adding into Firestore is by checking the key of the object. For instance, 'Electronics1' is the key of object that is present in the document, then increase the last digit by 1 and append into the document, which will be 'Electronics2'. My problem is that i use setIndex useState to record the largest digit in the document. However, for the first time, the index will always be 0 even when the 'value' changes. How can I make it to update whenever the value in the dropdown changes?

const [index, setIndex] = useState(0);
useEffect(() => {
    let isCancelled = false;
    async function dataToAdd() {
      if (value !== null) {
        const charLen = value.length;
        const docRef = doc(db, 'users', auth.currentUser.uid, 'expense', value);
        const docSnap = await getDoc(docRef);
        if (docSnap.exists()) {
          const singDocRec = docSnap.data();
          let num = 0;
          Object.entries(singDocRec).map(([key, record]) => {
            if (key != null || key != '' || key != undefined) {
              let i = key.slice(charLen, key.length);
              if (i > num) {
                num = i;
              }
            }
          });
          if (!isCancelled) {
            setIndex(parseInt(num)   1);
          }
        }
      }
    }
    dataToAdd();
    return () => {
      isCancelled = true;
    };
  }, [value]);

const createObj = value => {
    const concatStr = value.concat(index.toString());
    let obj = {};
    obj[concatStr] = {title: title, date: date, category: value};
    return obj;
  };

<DropDownPicker
          style={{
            borderRadius: 0,
          }}
          open={open}
          value={value}
          items={items}
          setOpen={setOpen}
          setValue={setValue}
          setItems={setItems}
        />
<TouchableOpacity
        onPress={() => {
          addFunc(value, createObj(value));
          navigation.navigate('Home');
        }}
        style={{
          width: 300,
          height: 50,
          marginTop: 20,
          borderWidth: 2,
          justifyContent: 'center',
        }}>
        <Text style={{textAlign: 'center', color: 'black', letterSpacing: 2}}>
          CONFIRM
        </Text>
      </TouchableOpacity>

CodePudding user response:

Why not try to call all the function inside your useEffect in the onChangeValue or onSelectItem ?onChangeValue={(value) => { callTheFunctionhere() }}

CodePudding user response:

The strick inequality operator is written !== in JavaScript :

Try : if (key !== null || key !== '' || key !== undefined)

  • Related