2

I have a file called Context.js in which I have a reducer. All of these are passed to other components using the Context API

const reducer = (state, action) => {
   switch (action.type) {
      case "SET_NAME":
         return {...state, name: action.payload}
      case "SET_LASTNAME":
         return {...state, lastname: action.payload}
      case "SET_EMAIL":
         return {...state, email: action.payload}
      default:
         return state
}

In numerous other components, I am trying to use Formik to work with forms, and would like to save the form info into state, so that if the form is accessed via other components, the info that has already been provided can be found there.

<label htmlFor="name">Nome</label>
    <Field maxLength="51"
           name="name" 
           value={name} 
           type="text" 
           onChange={(e) => dispatch({ type: "SET_NAME", payload: e.target.value })}
    />
    <ErrorMessage name="name" />

If I try to log the 'name', it works just fine, but as I leave the field it gives me the error message as if nothing had been typed.

I can't seem to work out how to use Formik along with useReducer or how to pass its info to other components

skyboyer
  • 22,209
  • 7
  • 57
  • 64
uber
  • 4,163
  • 5
  • 26
  • 55

1 Answers1

1

Formik handles forms in state so you might have to implement your form like this to help you send your input data to redux reducer: I hope this example helps

import React from "react";
import { Formik } from "formik";
import { useDispatch } from 'react-redux';

const MyForm = () => {
  const dispatch = useDispatch();

  return (
    <Formik
      initialValues={{ email: "" }}
      onSubmit={async values => {
        await new Promise(resolve => setTimeout(resolve, 500));
        alert(JSON.stringify(values, null, 2));
      }}
    >
      {props => {
        const {
          values,
          touched,
          errors,
          dirty,
          isSubmitting,
          handleChange,
          handleBlur,
          handleSubmit,
          handleReset
        } = props;
        return (
          <form onSubmit={handleSubmit}>
            <label htmlFor="email" style={{ display: "block" }}>
              Email
            </label>
            <input
              id="email"
              placeholder="Enter your email"
              type="text"
              value={values.email}
              onChange={(e) => {
                 console.log(e.target.value);
                 // send input data to formik
                 handleChange(e);

                 // dispatch to reducer
                 dispatch({ type: "SET_NAME", payload: e.target.value });
              }}
              onBlur={handleBlur}
              className={
                errors.email && touched.email
                  ? "text-input error"
                  : "text-input"
              }
            />
            {errors.email && touched.email && (
              <div className="input-feedback">{errors.email}</div>
            )}

            <button
              type="button"
              className="outline"
              onClick={handleReset}
              disabled={!dirty || isSubmitting}
            >
              Reset
            </button>
            <button type="submit" disabled={isSubmitting}>
              Submit
            </button>

            <pre
               style={{
                  background: '#f6f8fa',
                  fontSize: '.65rem',
                  padding: '.5rem',
               }}
            >
               <strong>props</strong> ={' '}
               {JSON.stringify(formik.values, null, 2)}
            </pre>
          </form>
        );
      }}
    </Formik>
  )
};

export default MyForm;
Chukwuemeka Ihedoro
  • 595
  • 1
  • 5
  • 17