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

910
Visualizações
get value when updated,outside of formik using useRef()

I'm trying to get the value of an autocomplete field outside of my formik component everytime it changes, and i did something like this:

const formRef=useRef<any>(null);
useEffect(() => {
    console.log("eee!!",formRef.current?.values?.flagTR)
},[formRef.current?.values]);
return (
        <Formik
            
            initialValues={initialValues}
            onSubmit={handleSumbit}
            enableReinitialize={true}
            validateOnChange={true}
            validationSchema={ProduitSchema}
            innerRef={formRef}
        >

the useEffect is triggered the first time the component renders,but then when i change the value of the autocomplete the useEffect doesn't get triggered. what should i do in order to trgger useEffect everytime a value from formik changes?

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

0

Hey so I don't think the approach you are going with here is going to work, it's really not what the useRef hook is for.

The correct approach for what it looks like you want to do is to properly use Formik's context to mapValuesToProps or get access to the values, errors, and validation states.

You can use withFormik() to set up your initial form values and mapValuesToProps. Then you can use within the form component formik's useFormikContext() which will give you access to values, errors, setValues, etc

export default withFormik({
    handleSubmit: () => {},
    validateOnChange: true,
    validateOnBlur: true,
    validateOnMount: true,
    mapPropsToValues: () => ({ name: '', email: '' }),
    initialValues: { name: '', email: '' }
  })(MyFormComponent)

In the MyFormComponent you can then call useFormikContext() and do whatever you want when the values change.

const { setValues, values, isValid, validateForm } = useFormikContext()

If for some reason this is not what you want to do, or it does not solve your problem, the only way to achieve what you want in React alone is to useState and and setState each time onChange eg

const MyFormComponent = () => {
   const [nameField, nameMeta] = useField(name)    
   const [emailField, emailMeta] = useField(email)
   const [formState, setFormState] = useState({name: '', email: ''})
    

   return (
     <Formik
      enableReinitialize
      validateOnBlur={false}
      initialValues={formState}
      onSubmit={() => {}}
    >
      {props => {
         const onChange = e => {
           const targetEl = e.target
           const fieldName = targetEl.name
              setFormState({
                  ...formState,
                  [fieldName]: targetEl.value
              })
              return props.handleChange(e)
          }
    
         return (
            <>
              <input {...nameField} onChange={onChange}>
              <input {...emailField} onChange={onChange}>
            </>
         )
      </Formik>
)
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