Copy testing for editing of post.
So I got the formReducer to work like so, exporting out these two functions and keeping the initialState and onChange() in the component itself.
import { useReducer } from "react"
const reducer = (state, { field, value }) => {
return {
...state,
[field]: value
}
}
const FormReducer = (initialState, reducer) => {
const [state, dispatch] = useReducer(initialState, reducer)
return [state, dispatch]
}
export { FormReducer, reducer }
Now, I’m trying to clear the state, dispatching all back to empty strings. Any ideas?
Mods: you can delete this or close. I solved it.
I passed different cases to the reducer in order to clear the state.
import { useReducer } from "react"
const init = (initialState) => {
return {initialState}
}
const reducer = (state, action) => {
switch (action.type) {
case 'form':
return { ...state, [action.field]: action.value }
case 'reset':
return init(action.payload)
}
}
const FormReducer = (initialState, reducer) => {
const [state, dispatch] = useReducer(initialState, reducer)
return [state, dispatch]
}
export { FormReducer, reducer }
Then calling like so:
const onChange = (e) => {
dispatch({ type: 'form', field: e.target.name, value: e.target.value })
}
And to clear the form:
dispatch({ type: 'reset', payload: initialState })