'Formik - setting dynamic values for select box
I have a address form containing country and state field when user selects country i want to fetch state list form backend and update state select box value list.
I have refereed below article for creating form. https://medium.com/@nphivu414/build-a-multi-step-form-with-react-hooks-formik-yup-and-materialui-fa4f73545598 enter image description here
Solution 1:[1]
First you can set initial values like below
const initialValues = {
otherValues: '',
address: {
line_1: '',
zip_code: '',
city: '',
state: '',
},
};
Then based on this initial value you can initiate state like below:
const [initialAddress, updateInitialAddress] = useState(initialValues);
After that, in the UseEffect you call API for address and you can update state like below:
//say your response set in "res" variable
updateInitialAddress({
otherValues: res.other_values,
address: {
line_1: res.line_1,
zip_code: res.zip_code,
city: res.city,
state: res.state,
},
});
In the formik you can then set:
initialValues={initialAddress}
And if your Formik Select Dropdown has the same name just like you initialised, then it will be automatically selected in the dropdown.
Thanks
Solution 2:[2]
const option = useMemo(() => {
return {
...formikOption,
initialValues: selectValue ? selectValue : {name: ""}
enableReinitialize: true
}
}, [selectValue]);
<formikComponen {...option }/>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Abu Sufian |
Solution 2 | Henry Ecker |