Hey guys, I am trying to clean up this code for forms and want to make the reducer usable for form inputs. I had this logic working in the component itself and decided to pull it out and make a custom reducer. This is what I have:
The reducer:
import { useReducer } from "react"
function formReducer(initialState, reducer) {
const [state, dispatch] = useReducer(initialState, reducer)
const reducer = (state, { field, value }) => {
return {
...state,
[field]: value
}
}
return [state, dispatch]
}
export { formReducer }
and I am using it in this component:
import React, { useState, useContext } from 'react'
import { CrudContext } from "../../context/crudContext"
import { Modal, Backdrop, Fade, TextField } from '@material-ui/core'
import { formReducer } from '../reducers/formReducer'
// Styles
import './styles/CreateArt.css'
import '../theme.css'
const initialState = {
title: '',
year: '',
medium: '',
url: '',
price: '',
}
// Admin — Create new art
const ComposeArt = () => {
This file has been truncated. show original
I don’t believe I am passing in the right values and not sure if I need onChange() or the initialState in the reducer file. Any help is much appreciate!
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 })