You have data stored in a state (possibly redux state)
and You are using formik to modify your data.
In code,
let { data } = props // from redux state
// suppose data is somewhat deep like
// data = {
// p1: {
// p11: {
// },
// p12: [{
// p122
// }, {
// p123
// }]
// },
// p2
// }
const handleSubmit = (values) => {
dispatch({
type: 'setData',
payload: {
data: values
}
})
})
<Formik initialValues={_.cloneDeep(data)} enableReinitialize onSubmit={handleSubmit} />
// reducer looks like
const reducer = (state={}, action) => {
return produce(state, (draft) => {
if (action.type === 'setData') {
draft.data = action.payload.data
}
})
}
notice I'm cloning data
with _.cloneDeep(data)
to prevent mutating the state.
When data is flat, it's safe to get away with {...data}
but when data are deep (have objects that have objects) it's not that easy
Is there an alternative way than deep cloning?
I was wondering if immer.js
could help here.