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

366
Visualizações
How to open Modal based on a function that changes the useState boolean in React?

I currently have the following useState and function:

const [displayTraits, setDisplayTraits] = useState(false);

const feelingsFilled = () => {
  const keysToCheck = ["anxiety", "mood", "cognition"];
  function validate(obj) {
    try {
      if (
        Object.keys(obj)
          .filter((key) => keysToCheck.includes(key))
          .every((key) => obj[key].counter > 0)
      ) {
        setDisplayTraits(true);
      } else {
        setDisplayTraits(false);
      }
    } catch (err) {
      console.log("error");
    }
  }

  validate(daily);
};
feelingsFilled();

which I then try to hook up with a modal so that when my function feelingsFilled() return true and changes the displayTraits to true, then it will open.

<Modal isVisible={displayTraits} />

I am trying to run this but get the following error

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I would need to make some assumptions on where the daily data comes from. If it is a changing prop or some other state, you can compute stuff based on that.

Using some state:

useEffect(() => {
  //computeYourStuffAndSetState
  const result = validate(daily);
  setDisplayTraits(result);
}, [daily]);
// The array param is a change-listener

Then you can bind your <Modal visible directly to the state variable, instead of a function.

Another example is to not use state at all and compute it everytime daily changes.

const showModal = useMemo(() => {
  return validate(daily);
}, [daily]);

useMemo and useEffect is a part of the built in react hooks.

Or you can just do something like:

const showModal = validate(daily);

This will also work, but will be less performant as it will recompute on every render

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