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

87
Visualizações
Accessing updated state inside the same function

I am having trouble accessing state after saving it, when calling the same function. My state is setup like this:

const perLanguageDefault = {
  calculated_skill: null,
  display_skill: null,
  published: false,
  premium: false,
  id: null,
};

  const [perLanguage, setPerLanguage] = useState(perLanguageDefault);

I have a save function inside one of my components as such:

  const _savePerLanguageArticle = async () => {
    if (perLanguage.id === null) {
      await _createPerLanguage();
    } else if (perLanguage.id !== null) {
      await _updatePerLanguage();
    }
    if (props.sentences.length !== 0 && perLanguage.id) {
      await _iterateSentences();
    }
    await _saveRulesArticle();
  };

If a perLanguage object doesn't exist, I create one in the database, and set it in state as such:

  const _createPerLanguage = async () => {
    const body = {
      published: perLanguage.published,
      premium: perLanguage.premium,
      article: props.article.id,
      language: props.lang_id,
      calculated_skill: perLanguage.calculated_skill,
      display_skill: perLanguage.display_skill,
    };
    try {
      const response = await api.post("perLanguageCreateAPI", {
        body: body,
      });
      await setPerLanguage(response.data);
    } catch (e) {
      console.log(e.response);
    }
  };

_saveRulesArticle above looks like this:

  const _saveRulesArticle = async () => {
    const newRules = props.rules.map((rule) => {
      let ruleobj = {};
      ruleobj["rule"] = rule;
      ruleobj["per_language"] = perLanguage.id;
      return ruleobj;
    });
    try {
      const response = await api.post("ruleMappingCreateAPI", {
        body: newRules,
      });
    } catch (e) {
      console.log(e.response);
      return;
    }
  };

However, because it's all within the same top function, _saveRulesArticle doesn't get access to the new perLanguage variable, it isn't updated, even though _createPerLanguage supposedly creates it and sets it.

I suspect there's some relation to this stack overflow page:

useState set method not reflecting change immediately

Most particularly the highest upvoted answer. I understand how that works for useEffect, but how would it work here? How do I update state inside a function, and then later inside that function, access the same updated state? Is this possible? Is this an anti-pattern?

about 4 years ago · Juan Pablo Isaza
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