Skip to content

Instantly share code, notes, and snippets.

@ever-dev
Last active September 25, 2020 10:37
Show Gist options
  • Save ever-dev/2311663634a226f76ee4e5af7d8bcb15 to your computer and use it in GitHub Desktop.
Save ever-dev/2311663634a226f76ee4e5af7d8bcb15 to your computer and use it in GitHub Desktop.
Regarding the components with initialValue prop

We often face (or sometimes we need to implement) initialValue which sets the value only for the first time when it's rendered. (Fortunately, I had a chance to implement initialValue not so long ago).
A good example is formik.

const [types, setTypes] = useEffect(null);
const getTypes = useCallback(async () => {
  const res = await getTypesAPI();
  setTypes(res);
}, []);
return <Formik initialValues={{type: types && types[0] || null}}>
  ...
  <select name="type" value="values.type" onChange="handleChange">
    {types.map((item, key) => <option value={item} key={key}>{item}</option>)}
  </select>
  ...
</Formik>

In this case, you will see the options in the selectbox but the initialValue for type is set to null and you will get validation error unless you select the option again.
to prevent this you will add the following code snippet before return statement

if (!types) {
  return <Loading />;
}

If you have any doubts, feel free to add comments! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment