I am using useReducer hook to for making the custom react hook but below in my code i cannot update state which im receiving from the dispatcher funnc

Here i want to update the state.value as i get data from the input and im using “name” tag to find what exactly key to be updated in the state.value. But here in my code im using useReducer hook to store data in state in my custom react hook useInput. but the problem im facing is i cannot udpate state here as you can see i am getting data from the dispatcher function but i cant save it to the state since i cannot access it from the reducer function.

import React from "react";

const reducer = (state, actions) => {
  switch (actions.type) {
    case "getData":
      return {
        ...state,
        value: { ...state.value, [actions.name]: actions.value }, // ****cannot acccess data here
      };
    default:
      return state;
  }
};

const useInput = () => {
  const defaultValue = {
    value: {
      fullname: "",
      address: "",
      pincode: "",
      city: "",
      phone: "",
    },
    touch: {
      fullname: false,
      address: false,
      pincode: false,
      city: false,
      phone: false,
    },
  };

  const [state, dispatcher] = React.useReducer(reducer, defaultValue);

  const getData = (e) => {
    const name = e.target.name;
    const value = e.target.value;
    dispatcher({ type: "getData", [name]: value }); // ****heres the dispatcher function
  };

  //   const blurHandler = (e) => {
  //     dispatcher({ type: "touch", value: true });
  //   };
  console.log(state.value);
  return {
    getData,
  };
};

export default useInput;


Answer

Try to pass a payload object containing a name and value property to the dispatch function:

const getData = (e) => {
    const name = e.target.name;
    const value = e.target.value;

    dispatcher({ type: "getData", payload: { name, value }});
};

You can then modify your reducer like this to edit the relative value:

const reducer = (state, actions) => {
    switch (actions.type) {
    case "getData":
        return {
            ...state,
            value: { ...state.value, [actions.payload.name]: actions.payload.value }, 
        };
    default:
        return state;
    }
};