Home > Back-end >  updating Formik initialValues with values from separate component
updating Formik initialValues with values from separate component

Time:12-04

I have a selectInput component made with React select which I have inside a Formik Form. I am trying to get my Formik values to update with the values coming back from React Select. What is the best way to get this done?

Inside my Formik Form:

  const initialValues = {
    firstName: '',
    lastName: '',
    jobPosition: '',
    email: '',
    phoneNumber: '',
    languages: [],
    files: []
  };

<SelectInput
    name='languages'
    options={languages}
    isMulti={true}
    onChange={handleChange}
    type='select'
/>

my SelectInput component:

import React from 'react'
import Select from "react-select";
import { inputStyles } from './styles';
import PropTypes from 'prop-types';
import { useField } from 'formik';

const SelectInput = ({ options, placeholder, isMulti, ...props }) => {


  const [field] = useField(props)


  return (
    <div style={{ marginTop: '1.5rem' }}>
      <Select
        {...field}
        styles={inputStyles}
        className="basic-single"
        classNamePrefix="select"
        isClearable={true}
        isSearchable={true}
        placeholder={placeholder}
        options={options}
        isMulti={isMulti}
      />
    </div>
  )
}

In its current state when selecting an option I receive a type Error:

Formik.tsx:600 Uncaught TypeError: Cannot read properties of undefined (reading 'type')

CodePudding user response:

I can't find the handleChange function you passed to onChange prop of SelectInput so I can't tell you what the problem in your code is but you can use useFormikContext hook to get setFieldValue method. You can pass this function to SelectInput from the parent component but the better approach is to move this function to your SelectInput component. You will have to read field name from props now. So it will look like this:

   const { setFieldValue } = useFormikContext();

   const handleChange = (option) => {
       setFieldValue(props.name, option);
   };

Add this code to your SelectInput component. Also note that you can use useFormikContext here because SelectInput is used inside form component of formik. If you want to define handleChange outside SelectInput component, you can give your form a ref and use ref.current.setFieldValue in parent component.

In case you need handleChange function outside Formik component, you can do this:

  const ref = useRef();
  
  const handleChange = (option) => {
     ref.current.setFieldValue("languages", option);
  };

  return (
     <Formik
        //other props
        innerRef={ref}
     >
     {/* your inputs */}
     </Formik>
  );
  • Related