Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

224
Visualizações
useState is not updating even after the value that trigger the update changes React Native

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>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda