UserContext.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import React, { createContext, useReducer, useContext } from "react";
  2. function formReducer(state, action) {
  3. switch (action.type) {
  4. case "RESULT_CHANGE":
  5. return { ...state, subtitle: action.payload };
  6. case "USERNAME_CHANGE":
  7. return { ...state, username: action.payload };
  8. case "EMAIL_CHANGE":
  9. return { ...state, email: action.payload };
  10. case "PASSWORD_CHANGE":
  11. return { ...state, password: action.payload };
  12. case "SAGITTA_CHANGE":
  13. return { ...state, sagitta: action.payload };
  14. case "HEIGHT_CHANGE":
  15. return { ...state, height: action.payload };
  16. case "WEIGHT_CHANGE":
  17. return { ...state, weight: action.payload };
  18. case "SUBMIT":
  19. return { ...state, isSubmitLoading: true };
  20. case "SUBMISSION_RECIEVED":
  21. return { ...state, isSubmitLoading: false, isSubmissionReceived: true };
  22. case "SUBMISSION_RECIEVED":
  23. return { ...state, isSubmitLoading: false, isSubmissionProcessed: true };
  24. default:
  25. throw new Error();
  26. }
  27. }
  28. const RegistrationFormContext = createContext();
  29. const regFormState = {
  30. result: "",
  31. username: "test",
  32. email: "",
  33. password: "",
  34. height: "",
  35. weight: "",
  36. sagitta: false,
  37. isSubmitLoading: false,
  38. isSubmissionReceived: false,
  39. isSubmissionProcessed: false
  40. };
  41. export const RegistrationFormProvider = ({ children }) => {
  42. const [state, dispatch] = useReducer(formReducer, regFormState);
  43. return (
  44. <RegistrationFormContext.Provider value={{ state, dispatch }}>
  45. {children}
  46. </RegistrationFormContext.Provider>
  47. );
  48. };
  49. export const useRegistrationFormState = () => {
  50. const context = useContext(RegistrationFormContext);
  51. if (context === undefined) {
  52. throw new Error(
  53. "userRegistrationFormState must be used within a RegistrationFormProvider"
  54. );
  55. }
  56. return context;
  57. }