I have been trying to maintain my reducer in the same file as my Context provider. However, I have not been able to figure out how to consume it in a component file.
inside of my Context function:
const reducer = (state, action) => {
switch (action.type) {
case "SET_LOCATION":
return {...state, location: action.payload}
case "SET_BUSINESS":
return {...state, business: action.payload}
case "SET_DATE":
return {...state, date: action.payload}
default:
return state
}
}
const [{location, business, date}, dispatch] = useReducer(reducer, {
location: "",
business: "",
date: "today",
})
return (
<ThemeContext.Provider value={{location, business, date, dispatch, reducer}}>
{props.children}
</ThemeContext.Provider>
)
at the component, inside of a form: I suspect I have not been using dispatch correctly, but couldn't figure out how to solve it by googling
const {location, business, date, dispatch, reducer} = useContext(ThemeContext)
return (
<form className="booking-form">
<h1>Book a service</h1>
<label>
Location
<input
type="text"
name="location"
value={location}
onChange={() => dispatch("SET_LOCATION")}
/>
</label>
<br/>
<br/>
<label>
Business
<input
type="text"
name="business"
value={business}
onChange={() => dispatch("SET_BUSINESS")}
/>
</label>
<h2 className="date">Date</h2>
<label>
<input
type="radio"
name="date"
value="today"
checked={date === "today"}
onChange={() => dispatch("SET_DATE")}
/>
Today
</label>
<label>
<input
type="radio"
name="date"
value="tomorrow"
checked={date === "tomorrow"}
onChange={() => dispatch("SET_DATE")}
/>
Tomorrow
</label>
<label>
<input
type="radio"
name="date"
value="other"
checked={date === "other"}
onChange={() => dispatch("SET_DATE")}
/>
Different date
</label>
{date === "other" ? <Calendar/> : <TimeGrid/>}
</form>