Set formik value from a component inside the formik

Viewed 68

Im working with formik, and I have an input that can be edited from an autocomplete and from a component that is inside the formik.

Its something like this:

<Formik
          initialValues={endUserLocationEdit}
          onSubmit={saveEndUserLocation}
        >
          {props => {
            const {
              values,
              touched,
              errors,
              status,
              isSubmitting,
              validateParcelContainer,
              setFieldValue,
              handleChange,
              handleSubmit,
              handleBlur

            } = props;

            return (<form className="form" onSubmit={handleSubmit}>

             <Autocomplete
                    fullWidth
                    id="rulLocationFk"
                    name="rulLocationFk"
                    value={values.rulLocationFk}
                    onChange={(event, newValue) => setFieldValue("rulLocationFk", newValue)}
                    onInputChange={(event, newInputValue) => {
                      searchLocation(values.locStatePk, newInputValue);
                    }}
                    getOptionSelected={(option, value) => value != null ? option.locName === value.locName : null}
                    getOptionLabel={(option) => option.locName}
                    options={locationList}
                        error={errors.locStatePk && touched.locStatePk}
                        renderInput={(params) => <TextField {...params} label="Location" variant="outlined" />}
                      />

         <MapCaller  > </MapCaller>

As you can see in the autocomplete I use setFieldValue to edit value={values.rulLocationFk}

Well, now inside the formik I also have a component that can edit the value of values.rulLocationFk

I call the component inside the formik like this:

<MapCaller  > </MapCaller>

How could I do to pass the parameter values.rulLocationFk to MapCaller, and could edit it inside of the MapCaller?

I think in something like:

  <MapCaller location={values.rulLocationFk} setLocation={setFieldValue} > </MapCaller>

But that doesnt work

Thanks

1 Answers

I agree with the comment above

An additional thought: This doesn't exactly solve the implementation you are using, but a quick pattern I like for using accessing value outside of formik is to set a ref to the innerRef Property of and then you can use the ref to access the formik values.

const formikRef = useRef(null)
<Formik
  innerRef={formikRef}
  initialValues={{
   valueName = "",
  ...

and then you can grab 
formikRef.current.values.valueName
Related