Home > Mobile >  How to use inline dispatch in useReducer Hook
How to use inline dispatch in useReducer Hook

Time:10-03

Here I have a form and I am managing my state with the help of useReducer and on every key stock I want to change value in my form like we use to do in useState which is known as two way binding and while dispatching useReducer if I point to external change function like this:

const idHandler = (e) => {
    dispatch({ type: "0", value: e.target.value });
  }

onChange={idHandler}

it works but I want to use inline function to bind my values and the problem is like when we use external function we recieve a event through we can bind value like:

function (event){
      event.target.value;
}

but here when I call dispatch inside inline anonymous function it doesnt recognize event (I want to send event.target.value as payload)

onChange={()=>dispatch({ type: "0", value: e.target.value })}

I also tried this.target.value but doesnt works so how am I supposed to deal with it:

import "./ProductForm.css";
import { useReducer } from "react";

const ProductForm = () => {
  const initialState = {
    product_id: "e11",
    product_name: "Masti kr ryian",
    product_quantity: 0,
    product_description: "",
    product_type: "",
    product_valid: "false",
    product_price: 0,
    product_title: "",
    product_image: "",
  };
  const reducer = (state, action) => {
    if (action.type === "0") {
      return { product_id: action.value };
    } else if (action.type === "1") {
      return state.product_name;
    } else {
      return "Error";
    }
  };
  const [state, dispatch] = useReducer(reducer, initialState);
 
  return (
    <form>
      <div className="form-group">
        <label>Product id</label>
        <input
          type="text"
          className="form-control"
          value={state.product_id}
          onChange={() => dispatch({ type: "0", val: event.target.value })}
        />
      </div>
      <div className="form-group">
        <label>Product Name</label>
        <input
          type="text"
          className="form-control"
          value={state.product_name}
          // onChange={(e) => dispatch("1")}
        />
      </div>
      <button type="submit" className="btn btn-primary mt-4">
        Submit
      </button>
    </form>
  );
};

export default ProductForm;
  

CodePudding user response:

Because you never declared the e parameter

onChange={e => dispatch({ type: "0", value: e.target.value })}
  • Related