How to pass the data from a state to a Formik initialValues?

Viewed 287

I have a component in my form that stores tags in a useState, but I don't know how to send that array to Formik's initialValues. I need to be able to send that data to the key called "tags" in Formik's initialValues, if someone could help me, thank you very much.

const AddProject2 = () => {
  const [tags, setTags] = useState([]);

  return (
    <Formik
      initialValues={{
        name: "",
        tags: [],
      }}
      onSubmit={(values) => {
        console.log(values);
      }}
    >
      {() => (
        <Form>
          <div>
            <label htmlFor="name">NameProject</label>
            <Field type="text" name="name" />
          </div>

          <ReactTagInput
            placeholder="Write the tags"
            tags={tags}
            onChange={(newTags) => setTags(newTags)}
          />

          <button type="submit">Send</button>
        </Form>
      )}
    </Formik>
  );
};

export default AddProject2;

1 Answers

If you just pass your tags state from useState() into initialValues as shown below, it should work. This would be shorthand for putting {name: "", tags: tags}

<Formik
      initialValues={{
        name: "",
        tags,
      }}
      onSubmit={(values) => {
        console.log(values);
      }}
    >

-edit- Regarding the new issue in your comment.

Perhaps it's an issue with the way Formik works. Looking at their docs, it appears the way to handle control of inputs with formic doesn't directly use onChange, instead you would need to pass in a spread of props with {...formik.getFieldProps('tags')}

so:

{formik => (
        <Form>
          <div>
            <label htmlFor="name">NameProject</label>
            <Field type="text" name="name" />
          </div>

          <ReactTagInput
            placeholder="Write the tags"
            tags={tags}
            {...formik.getFieldProps('tags')}
          />
)}

Whether this would be compatible with ReactTagInput, I don't know but it's worth a try.

Related