Formik catch-22 - reactjs

I'm new to React and I've run into a catch 22 situation when using Formik that I seem to have a mental block with. If I use withFormik() then my component can't use hooks in its submit handler.
import React, { useEffect } from "react";
import { Form, Field, withFormik } from "formik";
import { useDatabase, useAlerts } from "./Hooks";
const MyForm = props => {
const { resetForm, dirty, isSubmitting, setSubmitting } = props;
const { loadData, saveData } = useDatabase();
const { success } = useAlerts();
const reset = data => resetForm({ values: data });
useEffect(() => {
loadData().then(data => reset(data));
}, []);
// Problem: How can I execute this on submit?
const handleSubmit = async values => {
await saveData(values);
reset(values);
success("Values saved");
setSubmitting(false);
};
return (
<Form>
<h1>Catch 22</h1>
<Field
name="firstName"
placeholder="First name"
readOnly={isSubmitting}
/>
<Field name="lastName" placeholder="Last name" readOnly={isSubmitting} />
<input disabled={!dirty} type="submit" />
<input type="reset" />
</Form>
);
};
export default withFormik({
mapPropsToValues: () => ({
firstName: "",
lastName: ""
}),
enableReinitialize: true,
handleSubmit: () => {
// Has no access to saveData() and success() hook methods
}
})(MyForm);
https://codesandbox.io/s/sleepy-blackburn-q1mt4?file=/src/MyForm.js
Alternatively if I don't use withFormik then I can't reset the form when my data has loaded because I don't have a reference to resetForm.
import React, { useEffect } from "react";
import { Form, Field, Formik } from "formik";
import { useDatabase, useAlerts } from "./Hooks";
const MyForm = props => {
const { loadData, saveData } = useDatabase();
const { success } = useAlerts();
// Problem: how can I reset the form on data load?
useEffect(() => {
loadData().then(data => resetForm({ values: data }));
}, []);
const initialValues = {
firstName: "",
lastName: ""
};
const handleSubmit = async (values, { setSubmitting, resetForm }) => {
await saveData(values);
resetForm({ values });
success("Values saved");
setSubmitting(false);
};
return (
<Formik
initialValues={initialValues}
onSubmit={handleSubmit}
enableReinitialize={true}
>
{({ isSubmitting, dirty }) => (
<Form>
<h1>Catch 22</h1>
<Field
name="firstName"
placeholder="First name"
readOnly={isSubmitting}
/>
<Field
name="lastName"
placeholder="Last name"
readOnly={isSubmitting}
/>
<input disabled={!dirty} type="submit" />
<input type="reset" />
</Form>
)}
</Formik>
);
};
export default MyForm;
https://codesandbox.io/s/hardcore-sound-048wf?file=/src/MyForm.js
What would be the best way to do this?

It seems that writing out the problem triggered some mind-cogs to start turning and I came up with a possible solution.
I introduced a context like this...
import React, { useState, useContext } from "react";
import { useDatabase } from "./Hooks";
export const DataContext = React.createContext(null);
export const DataContextConsumer = DataContext.Consumer;
export const useDataContext = () => useContext(DataContext);
export const DataContextProvider = props => {
const [data, setData] = useState({
firstName: "",
lastName: ""
});
const { loadData, saveData } = useDatabase();
const load = async () => setData(await loadData());
const save = async newData => await saveData(newData);
const contextValues = { load, save, data };
return (
<DataContext.Provider value={contextValues}>
{props.children}
</DataContext.Provider>
);
};
export const withDataContext = () => WrappedComponent => props => (
<DataContextProvider>
<WrappedComponent {...props} />
</DataContextProvider>
);
export default {
DataContext,
DataContextConsumer,
DataContextProvider,
useDataContext,
withDataContext
};
And then passed its data to Formik's initialValues. Now Formik gets the new values on load and I can call the save hooks in the submit hander.
import React, { useEffect } from "react";
import { Form, Field, Formik } from "formik";
import { withDataContext, useDataContext } from "./DataContext";
import { useAlerts } from "./Hooks";
const MyForm = () => {
const { load, save, data } = useDataContext();
const { success } = useAlerts();
useEffect(() => {
load();
}, []);
const handleSubmit = async (values, { setSubmitting, resetForm }) => {
await save(values);
resetForm({ values });
success("Values saved " + JSON.stringify(values));
setSubmitting(false);
};
return (
<Formik
initialValues={data}
onSubmit={handleSubmit}
enableReinitialize={true}
>
{({ isSubmitting, dirty }) => (
<Form>
<h1>Catch 22</h1>
<Field
name="firstName"
placeholder="First name"
readOnly={isSubmitting}
/>
<Field
name="lastName"
placeholder="Last name"
readOnly={isSubmitting}
/>
<input disabled={!dirty} type="submit" />
<input type="reset" />
</Form>
)}
</Formik>
);
};
export default withDataContext()(MyForm);
https://codesandbox.io/s/throbbing-cache-txnit?file=/src/MyForm.js
Perhaps this is a classic case of solving a React problem by lifting state.

You can lift the form inside the render prop for formik up into a new component allowing you to use hooks inside it. Now you can move the loadData effect into the lifted form and know that you are now defining the effect inside of both scopes where you can get access to resetForm via the render props and loadData via the useDatabase hook.
const LiftedForm = ({ isSubmitting, dirty, resetForm }) => {
const { loadData } = useDatabase();
useEffect(() => {
loadData().then((data) => resetForm({ values: data }));
}, [loadData, resetForm]);
return (
<Form>
<h1>Catch 22</h1>
<Field
name="firstName"
placeholder="First name"
readOnly={isSubmitting}
/>
<Field name="lastName" placeholder="Last name" readOnly={isSubmitting} />
<input disabled={!dirty} type="submit" />
<input type="reset" />
</Form>
);
};
and passing the formik bag via the render props right to the new lifted form component.
<Formik
initialValues={initialValues}
onSubmit={handleSubmit}
enableReinitialize={true}
>
{(props) => <LiftedForm {...props} />}
</Formik>
The handleSubmit needs no changing because it already receives everything it needs in the callback and has access to saveData and success via hooks.
const { saveData } = useDatabase();
const { success } = useAlerts();
const handleSubmit = async (values, { setSubmitting, resetForm }) => {
await saveData(values);
resetForm({ values });
success("Values saved");
setSubmitting(false);
};
the codesandbox for that

Related

handleSubmit to call another function with event parameter

This is React JS.
I had a nice working sendData function that creates a new record on my json file.
It worked nice until I decided to add useForm to add some yup resolvers.
Now in the <form> tag here is onSubmit={}.
If I write here
<form onSubmit={handleSubmit(sendData(), onSubmit)}>, I get the error and nothing works as before.
enter image description here
I except to understand how handleSubmit works and how to resolve this problem.
Thanks in advance, guys!
my code:
import React, { useState } from 'react';
import { useForm } from 'react-hook-form';
import { Link, useNavigate } from 'react-router-dom';
import Confirmation from './Confirmation';
import * as yup from 'yup';
import { yupResolver } from '#hookform/resolvers/yup';
const schema = yup.object().shape({
name: yup.string().required(),
age: yup.number().positive().required(),
salary: yup.number().positive().required(),
email: yup.string().required(),
})
.required();
export default function LogIn() {
const { register, handleSubmit, formState: { errors }, } = useForm({
resolver: yupResolver(schema),
});
// for redirection
let navigate = useNavigate();
// modal for ghost mode
const [show, setShow] = useState(false);
const [details, setDetails] = useState({
name: '',
age: 0,
salary: 0,
email: ''
})
const sendData = async (event) => {
event.preventDefault()
const {name, age, salary, email} = details;
const res = await fetch("i hide the link :D",
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name, age, salary, email
})
})
navigate("/main");
}
const onSubmit = (data) => {
console.log(data)
}
return (
<div>
{show && <Confirmation show={show} setShow={setShow} />}
<div className="form-center">
<h1>Few Information</h1>
<form onSubmit={handleSubmit(sendData(), onSubmit)}>
<div className="form-controll">
<input type="text" {...register('name')} placeholder="Name"
onChange={(e) => setDetails({...details,name:e.target.value})}/>
{errors.name?.message && <p>{errors.name?.message}</p>}
<input type="number" {...register('age')} placeholder="Age"
onChange={(e) => setDetails({...details,age:e.target.value})}/>
{errors.age?.message && <p>{errors.age?.message}</p>}
<input type="number" {...register('salary')} placeholder="Salary in $"
onChange={(e) => setDetails({...details,salary:e.target.value})}/>
{errors.salary?.message && <p>{errors.salary?.message}</p>}
<input type="email" {...register('email')} placeholder="Email"
onChange={(e) => setDetails({...details,email:e.target.value})}/>
{errors.email?.message && <p>{errors.email?.message}</p>}
</div>
<div className="forgot">
Don't want to share data?<br></br>
<button onClick={() => {setShow(true)}}>Ghost mode</button>
</div>
<div className="btn">
<input type='submit' value='Go' />
</div>
</form>
</div>
</div>
)
}
handleSubmit function is a wrapper for react-hook-form to manage your data inputs, validation, errors, etc.. before calling your own sendData function.
Consider doing:
export default function LogIn() {
const sendData = async (data) => {
const {name} = data;
// your post request
}
return (
<form onSubmit={handleSubmit(sendData}> // remove the useless onSubmit
<input
type="text"
{...register('name')}
placeholder="Name"
// remove the onChange prop
/>
</form>
)
}

Set props Data to context in formik

I have two components inside contact page. One is contact form and another is FormData where I'm showing what the user is typing in forms field. I also have a context where I want to store the form data. But in formik there are built-in props, from there I can access the values but from inside the form. But I want to pass the values outside the form to the context so that I can access this data from the FormData component.
Contact Form
import React, { useContext, useEffect } from "react";
import { useFormik } from "formik";
import { Formik } from "formik";
import { ContentContext } from "../Context";
import { FormData } from "./index";
const ContactForm = () => {
const [content, setContent] = useContext(ContentContext);
// useEffect(() => {
// setContent({
// ...content,
// contactFormData: props,
// });
// }, [props]);
// console.log(content);
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;
// setContent({
// ...content,
// contactFormData: 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={handleChange}
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>
{/* <FormData props={props} />; */}
</form>
);
}}
</Formik>
);
};
export default ContactForm;
context
import React, { useState, createContext } from "react";
export const ContentContext = createContext();
export const ContentProvider = ({ children }) => {
const [content, setContent] = useState({
contactFormData: {
email: "",
},
});
return (
<ContentContext.Provider value={[content, setContent]}>
{children}
</ContentContext.Provider>
);
};
setting the context inside the form causes infinite loop. How do I save props to context?

Redux dispatch with React Final Form

I'm trying to understand why dispatch is not available in my actions to no avail. Here is what I tried.
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Field, Form } from 'react-final-form';
import { createProfile } from '../../actions/actions_members';
const onSubmit = async (values) => {
createProfile(values)
}
const Signup = () => (
<Form
onSubmit={onSubmit}
render={({ handleSubmit, submitting, pristine, values }) => (
<form onSubmit={handleSubmit} >
<label>Email:</label>
<Field type='text' className='input' component="input" type="text" name='email'/>
<label>Password:</label>
<Field className='input' component="input" type="password" name='password' />
{/*<label>Confirm password:</label>
<input type='password' className='input' name='password' {...password} />*/}
<button type="submit" disabled={submitting || pristine}>
Submit
</button>
</form>
)}
/>
)
export default connect()(Signup)
And here is my actions_members file
import * as C from './actions_const.js'
import { post, get } from '../helpers/apiConnection.js'
const createProfile = (value, dispatch) => {
var data = {
ep: "EP_SIGNUP",
payload : {
email: value.email,
password: value.password
}
}
post(data).then((result)=>dispatch({type:C.MEMBER_CREATE}));
}
export { createProfile }
I don't know how to pass dispatch to my createProfile action
You just have to pass it in from the onSubmit function.
const dispatch = useDispatch();
const onSubmit = async (values) => {
createProfile(values, dispatch)
}
The other option would be to import the store in your action_members file and use store.dispatch, which amounts to the same thing.
import * as C from './actions_const.js'
import { post, get } from '../helpers/apiConnection.js'
import store from '../whereverReduxStoreIsSetup.js';
const createProfile = (value) => {
var data = {
ep: "EP_SIGNUP",
payload : {
email: value.email,
password: value.password
}
}
post(data).then((result)=>store.dispatch({type:C.MEMBER_CREATE}));
}
export { createProfile }

Submitting a Formik Form on Unmount

Is it possible to submit a Formik Form without having a submit button?
For example submitting the Form when the component unmounts so the user doesn't need to click a button to save.
Think of something like that:
import React from "react";
import { Formik, Form, Field } from "formik";
const Example = () => {
useEffect(() => {
return () => {
//trigger Submit or send Request with Form Values from here
};
}, []);
return (
<Formik
initialValues={{
firstName: "",
lastName: "",
}}
onSubmit={(values, { setSubmitting }) => {
//send Request
}}
>
{() => (
<Form>
<Field name="firstName" />
<Field name="lastName" />
</Form>
)}
</Formik>
);
};
export default Example;
You can create a functional component that auto-submits. By having it render inside the component, you have reference to the context of the form. You can use:
import { useFormikContext } from 'formik';
function AutoSubmitToken() {
// Grab values and submitForm from context
const { values, submitForm } = useFormikContext();
React.useEffect(() => {
return submitForm;
}, [submitForm]);
return null;
};
You can use it under the component as such
<Form>
<Field name="token" type="tel" />
<AutoSubmitToken />
</Form>
You can read all about it here

Fetch and use response to change state in React

I would like to change the state of a component based on the response of a PUT request using react-refetch.
Especially when the response of the PUT is unsuccessful, as is the case with for example a 500 response.
The following example is an example in a form. When a user submits the form it should then fire off a PUT.
If the PUT response is fulfilled, it should reset the form. Otherwise nothing should happen, and the user should be able to retry.
./MyForm.jsx
import React from "react";
import PropTypes from "prop-types";
import { PromiseState } from "react-refetch";
import { Formik, Form, Field, ErrorMessage } from "formik";
import ResetOnSuccess from "./ResetOnSuccess";
const MyForm = ({ settingsPut, settingsPutResponse }) => {
const submitForm = (values, formik) => {
settingsPut(true);
// Here it should pick up the settingsPutResponse,
// and then do the following ONLY if it's successful:
//
// formik.resetForm({ values });
// window.scrollTo(0, 0);
};
return (
<div>
<Formik
noValidate
initialValues={{ name: "", password: "" }}
onSubmit={submitForm}
>
{({ dirty }) => (
<Form>
<ResetOnSuccess settingsPutResponse={settingsPutResponse} />
<Field type="text" name="name" />
<ErrorMessage name="name" component="div" />
<Field type="password" name="password" />
<ErrorMessage name="password" component="div" />
<button type="submit" disabled={dirty !== null ? !dirty : false}>
Submit
</button>
{settingsPutResponse && settingsPutResponse.rejected && (
<p style={{ color: "red" }}>Please try again</p>
)}
</Form>
)}
</Formik>
</div>
);
};
MyForm.propTypes = {
settingsPut: PropTypes.func.isRequired,
settingsPutResponse: PropTypes.instanceOf(PromiseState)
};
MyForm.defaultProps = {
userSettingsPutResponse: null
};
export default MyForm;
I might have a solution by creating a component:
./ResetOnSuccess.jsx
import React, { useEffect, useState } from "react";
import { useFormikContext } from "formik";
import PropTypes from "prop-types";
import { PromiseState } from "react-refetch";
const ResetOnSuccess = ({ settingsPutResponse }) => {
const { values, resetForm } = useFormikContext();
const [success, setSuccess] = useState(false);
useEffect(() => {
if (settingsPutResponse && settingsPutResponse.fulfilled) {
setSuccess(true);
}
}, [settingsPutResponse]);
// only if settingsPutResponse is fulfilled will it reset the form
if (success) {
resetForm({ values });
window.scrollTo(0, 0);
setSuccess(false);
}
return null;
};
ResetOnSuccess.propTypes = { settingsPutResponse: PropTypes.instanceOf(PromiseState) };
ResetOnSuccess.defaultProps = { settingsPutResponse: null };
export default ResetOnSuccess;
And then in ./MyForm.jsx add the reset component:
<Formik
noValidate
initialValues={{ name: "", password: "" }}
onSubmit={submitForm}
>
{({ dirty }) => (
<Form>
<ResetOnSuccess settingsPutResponse={settingsPutResponse} />
<Field type="text" name="name" />
<ErrorMessage name="name" component="div" />
<ResetOnSuccess settingsPutResponse={settingsPutResponse} />
// etc...
But since it's a component that returns a 'null'. This feels a bit like an anti-pattern.
Is there a better way?
I've created an codesandbox example here: https://codesandbox.io/s/quizzical-johnson-dberw

Resources