import React, { useReducer } from 'react' import { getDays } from '../lib/dateHelper' export const WizardContext = React.createContext() export const ACTIONS = { NEXT_STEP: 'nextStep', PREV_STEP: 'prevStep', SET_MULTIPLE_DAYS: 'setMultipleDays', SET_DATE: 'setDate', SET_FOCUSED_INPUT: 'setFocusedInput', SET_PICKUP_TIME: 'setPickupTime', SET_DROPOFF_TIME: 'setDropoffTime', SUBMIT: 'submit', } 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_MULTIPLE_DAYS: return { ...state, multipleDays: action.payload, focusedInput: undefined, startDate: undefined, endDate: undefined, days: [], } case ACTIONS.SET_DATE: return { ...state, startDate: action.payload.startDate, endDate: action.payload.endDate, days: getDays({ startDate: action.payload.startDate || state.startDate, endDate: action.payload.endDate || state.endDate, multipleDays: state.multipleDays, }), } case ACTIONS.SET_FOCUSED_INPUT: return { ...state, focusedInput: action.payload } case ACTIONS.SET_PICKUP_TIME: return { ...state, pickupTime: action.payload } case ACTIONS.SET_DROPOFF_TIME: return { ...state, dropoffTime: action.payload } case ACTIONS.SUBMIT: // TODO: should probably not kick this off here, that sucks createBooking(state) return { ...state } 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, days } = state 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, days }), }) return response.json() } const initialState = { name: 'Thomas Ruoff', email: 'thomasruoff@gmail.com', currentStep: 0, multipleDays: null, 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) return ( {children} ) }