{"size": 1635, "ext": "js", "max_stars_repo_path": "food-order-app/src/hooks/use-input.js", "max_stars_repo_name": "christopher-adolphe/learning-react-v2", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "food-order-app/src/hooks/use-input.js", "max_issues_repo_name": "christopher-adolphe/learning-react-v2", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "food-order-app/src/hooks/use-input.js", "max_forks_repo_name": "christopher-adolphe/learning-react-v2", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 22.0945945946, "max_line_length": 86, "alphanum_fraction": 0.5944954128}
import { useReducer, useCallback } from 'react';

const ACTIONS = {
  CHANGE: 'CHANGE',
  BLUR: 'BLUR',
  VALIDATE: 'VALIDATE',
  RESET: 'RESET'
};

const initialState = { value: '', isTouched: false, isValid: true, error: null };

const inputReducer = (state, action) => {
  const { type, payload } = action;

  switch (type) {
    case ACTIONS.CHANGE:
      
      return { ...state, value: payload.value };

    case ACTIONS.BLUR:
      
      return { ...state, isTouched: true };

    case ACTIONS.VALIDATE:
      const [ validators ] = payload.validators;
      let error = null;

      for (const validator of validators) {
        error = validator(state.value);
        
        if (error !== null) {
          break;
        }
      }

      const isValid = error !== null ? false : true;
      
      return { ...state, isValid, error };

    case ACTIONS.RESET:
      
      return { value: '', isTouched: false, isValid: true };
  
    default:
      return state;
  }
};

function useInput() {
  const [ input, dispatchInput ] = useReducer(inputReducer, initialState);

  const handleChange = (event) => {
    dispatchInput({ type: ACTIONS.CHANGE, payload: { value: event.target.value } });
  };

  const handleBlur = () => {
    dispatchInput({ type: ACTIONS.BLUR });
  };

  const handleValidation = useCallback((...validators) => {
    dispatchInput({ type: ACTIONS.VALIDATE, payload: { validators: [ validators ] }});
  }, []);

  const handleReset = () => {
    dispatchInput({ type: ACTIONS.RESET });
  };



  return { input, handleChange, handleBlur, handleValidation, handleReset };
};

export default useInput;
