improve client a bit

This commit is contained in:
Thomas Ruoff
2020-08-01 14:31:34 +02:00
parent 027cf45faa
commit 9570c6996c
6 changed files with 126 additions and 28 deletions

View File

@@ -4,6 +4,9 @@ export const WizardContext = React.createContext()
export const ACTIONS = {
SET_FORM_DATA: 'setFormData',
POST_DATA: 'postData',
POST_DATA_ERROR: 'postDataError',
POST_DATA_SUCCESS: 'postDataSuccess',
}
function reducer(state, action) {
@@ -16,6 +19,31 @@ function reducer(state, action) {
...action.payload,
},
}
case ACTIONS.POST_DATA:
return {
...state,
postData: true,
postDataError: null,
postDataSuccess: null,
}
case ACTIONS.POST_DATA_ERROR:
return {
...state,
postData: false,
postDataError: action.payload,
postDataSuccess: null,
}
case ACTIONS.POST_DATA_SUCCESS:
return {
...state,
formData: {
...state.formData,
...action.payload,
},
postData: false,
postDataError: null,
postDataSuccess: true,
}
default:
throw new Error(`Unkown Action type ${action.type}`)
}
@@ -28,8 +56,26 @@ function debugReducer(state, action) {
return newState
}
async function createBooking(state) {
const { name, email, startDate, endDate } = state.formData
const initialState = {
postData: false,
postDataError: null,
postDataSuccess: null,
formData: {
multipleDays: true,
//startDate: '2020-08-10',
//endDate: '2020-08-17',
//purpose: 'Sommerlager 2021',
//org: 'VCP Rosenfeld',
//destination: 'Lüneburger Heide',
//name: 'Thomas Ruoff',
//email: 'thomasruoff@gmail.com',
//street: 'Mömpelgardgasse 25',
//zip: '72348',
//city: 'Rosenfeld',
},
}
async function createBooking(formData) {
const response = await fetch('/api/booking', {
method: 'POST',
mode: 'cors',
@@ -39,23 +85,14 @@ async function createBooking(state) {
'Content-Type': 'application/json',
},
referrerPolicy: 'no-referrer',
body: JSON.stringify({ name, email, startDate, endDate }),
body: JSON.stringify(formData),
})
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
@@ -72,9 +109,21 @@ export default function WizardStore({ children }) {
})
}
const onSubmit = async () => {
dispatch({ type: ACTIONS.POST_DATA })
try {
const bookingData = await createBooking(state.formData)
dispatch({ type: ACTIONS.POST_DATA_SUCCESS, payload: bookingData })
} catch (error) {
console.error(error)
dispatch({ type: ACTIONS.POST_DATA_ERROR, payload: error.message })
}
}
return (
<WizardContext.Provider
value={{ state, dispatch, onChangeEvent, onChange, storeBooking }}
value={{ state, dispatch, onChangeEvent, onChange, onSubmit }}
>
{children}
</WizardContext.Provider>