Files
pfadi-bussle/context/wizardStore.js
2020-07-27 00:42:08 +02:00

87 lines
1.9 KiB
JavaScript

import React, { useReducer } from 'react'
export const WizardContext = React.createContext()
export const ACTIONS = {
NEXT_STEP: 'nextStep',
PREV_STEP: 'prevStep',
SET_FORM_DATA: 'setFormData',
}
function reducer(state, action) {
switch (action.type) {
case ACTIONS.NEXT_STEP:
return {
...state,
currentStep: state.currentStep + 1, // wizards steps unkown here
}
case ACTIONS.PREV_STEP:
return {
...state,
currentStep: Math.max(0, state.currentStep - 1),
}
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: {
name: 'Thomas Ruoff',
email: 'thomasruoff@gmail.com',
multipleDays: null,
},
currentStep: 0,
bookedOn: [
'2020-07-10',
'2020-07-11',
'2020-07-12',
'2020-07-23',
'2020-08-01',
],
}
export default function WizardStore({ children }) {
const [state, dispatch] = useReducer(debugReducer, initialState)
const onSubmit = () => createBooking(state)
return (
<WizardContext.Provider value={{ state, dispatch, onSubmit }}>
{children}
</WizardContext.Provider>
)
}