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

123
Visualizações
Can't update parent component state with React UseState

im facing this weird behavior when trying to update the parent component with an set function to the child with props this hook is to open and close the modal to edit an element

//PARENT FILE

//hook
  const [isEditModalOpen, setEditModalOpen] = useState(false) 

//more code...

//modal
 {isEditModalOpen && <EditExcerciseModal setEditModalOpen={setEditModalOpen} isEditModalOpen={isEditModalOpen} />}


and this is the child code

//CHILD FILE

export const EditExcerciseModal = ({setEditModalOpen, excerciseInfo,fetchExcercisesFromRoutine}) 
//more code etc etc

   <div className="addExcerciseModalContainer">
                <span onClick={() =>{ setEditModalOpen(false) }} className="xModal">X</span>

i checked and the onClick is working. if i change the parent state manually the Modal works fine and closes.

the weird case when it its working is when instead of calling the set function i create a function with a setTimeout without time like this:

  function closeModal(){

        setTimeout(() => {  setEditModalOpen(false)}, 0);
        
    }

any ideas? thanks for the help

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You need to create a separation of concern. A Modal consists of three parts

  • The Modal of its Self.
  • The Content of the Modal.
  • And the container of the two.

You should be using the useState() hook and calling setEditModalOpen in the same containing component.

You need to make sure that you're declaring and setting state inside the same component.

// children would be the content of the modal
const Modal = ({ children, selector, open, setOpen }) => {
  // we need the useEffect hook so that when we change open to false
  // the modal component will re-render and the portal will not be created
  useEffect(() => {
    setOpen(false);
    //provide useEffect hook with clean up.
    return () => setOpen(true);
  }, [selector]);

  return open ? createPortal(children, selector) : null;
};

export const EditExerciseModal = ({ close }) => {
  return (
    <div>
      {/* Instead of creating a handler inside this component we can create it in it's parent element */}
      <span onClick={close}>X</span>
      {/* Content */}
    </div>
  );
};

export const ModalBtn = () => {
  const [isEditModalOpen, setEditModalOpen] = useState(false);
  // this is where it all comes together,
  // our button element will keep track of the isEditModalOpen variable,
  // which in turn will update  both child elements
  // when true useEffect hook will re-render Modal Component only now it "will" createPortal()
  // when our EditExerciseModal alls close it will set change the isEditModalOpen to false
  // which will be passed to the Modal component which
  // will then cause the component to re-render and not call createPortal()

  return (
    <>
      <button onClick={() => setEditModalOpen(true)}>EditExerciseModal</button>
      {setEditModalOpen && (
        <Modal
          open={isEditModalOpen}
          setOpen={setEditModalOpen}
          selector={'#portal'}>
          <div className='overlay'>
            <EditExerciseModal close={() => setEditModalOpen(false)} />
          </div>
        </Modal>
      )}
    </>
  );
};
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