Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Looking for a better solution #1800

Open
minhth-1529 opened this issue Sep 6, 2019 · 1 comment
Open

Looking for a better solution #1800

minhth-1529 opened this issue Sep 6, 2019 · 1 comment
Labels

Comments

@minhth-1529
Copy link

❓I am implementing a feature update user information by formik. When componentDidMount I use setFieldValue() to each field but it not working, and I found settimeout but I felt that some trick. Please give me some a better solution.

`componentDidMount() {
const { setFieldValue, location } = this.props;
const stringObject = queryString.parse(location.search);

    setTimeout(() => {
        setFieldValue('locationFrom', stringObject.from);
        setFieldValue('locationTo', stringObject.to);
        setFieldValue('startTime', moment(stringObject.startTime));
        setFieldValue('slot', stringObject.slot);
    }, 1);
}`
@johnrom
Copy link
Collaborator

johnrom commented Sep 7, 2019

It looks like you're trying to update the value within formik on mount. Instead, you can initialize formik with those values from the very beginning by lifting your state up a bit.

const selectInitialValues = (values) => ({
  locationFrom: values.from,
  locationTo: values.to,
  startTime: moment(values.startTime),
  slot: values.slot, 
)};

// props might have values from redux or something else
const MyForm = (props) => (
    <Formik initialValues={selectInitialValues(props.initialValues)} {...restOfFormikProps}>
        <Field name="locationFrom" /> // will have value returned from selectInitialValues(props.initialValues)
    </Formik>
);

Note you can add <Formik enableReinitialize={true} /> to re-initialize the form once props have changed in response to a Redux request, but you'll want to make sure it only happens once or twice because your form will re-render each time props change.

If you create a sandbox where you've tried this with the class-based version, I can fork it and describe how that would work. Writing with classes is a bit verbose for answering a question, though, so I've described it with function components. Hope it helps!

@stale stale bot added the stale label Nov 6, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants