mirror of
https://github.com/tomru/pfadi-bussle.git
synced 2026-03-03 22:47:15 +01:00
83 lines
1.7 KiB
JavaScript
83 lines
1.7 KiB
JavaScript
import React, { useReducer } from 'react'
|
|
|
|
export const WizardContext = React.createContext()
|
|
|
|
export const ACTIONS = {
|
|
SET_FORM_DATA: 'setFormData',
|
|
}
|
|
|
|
function reducer(state, action) {
|
|
switch (action.type) {
|
|
case ACTIONS.SET_FORM_DATA:
|
|
return {
|
|
...state,
|
|
formData: {
|
|
...state.formData,
|
|
...action.payload,
|
|
},
|
|
}
|
|
default:
|
|
throw new Error(`Unkown Action type ${action.type}`)
|
|
}
|
|
}
|
|
|
|
function debugReducer(state, action) {
|
|
console.debug('applying action', action)
|
|
const newState = reducer(state, action)
|
|
console.debug(newState)
|
|
return newState
|
|
}
|
|
|
|
async function createBooking(state) {
|
|
const { name, email, startDate, endDate } = state.formData
|
|
const response = await fetch('/api/booking', {
|
|
method: 'POST',
|
|
mode: 'cors',
|
|
cache: 'no-cache',
|
|
credentials: 'same-origin',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
referrerPolicy: 'no-referrer',
|
|
body: JSON.stringify({ name, email, startDate, endDate }),
|
|
})
|
|
|
|
return response.json()
|
|
}
|
|
|
|
const initialState = {
|
|
formData: {
|
|
multipleDays: null,
|
|
},
|
|
}
|
|
|
|
export default function WizardStore({ children }) {
|
|
const [state, dispatch] = useReducer(debugReducer, initialState)
|
|
|
|
const storeBooking = () => createBooking(state)
|
|
|
|
const onChangeEvent = (event) => {
|
|
const { name, value } = event.target
|
|
|
|
dispatch({
|
|
type: ACTIONS.SET_FORM_DATA,
|
|
payload: { [name]: value },
|
|
})
|
|
}
|
|
|
|
const onChange = (data) => {
|
|
dispatch({
|
|
type: ACTIONS.SET_FORM_DATA,
|
|
payload: data,
|
|
})
|
|
}
|
|
|
|
return (
|
|
<WizardContext.Provider
|
|
value={{ state, dispatch, onChangeEvent, onChange, storeBooking }}
|
|
>
|
|
{children}
|
|
</WizardContext.Provider>
|
|
)
|
|
}
|