javascriptreactjsdomreact-contextuse-reducer

dispatch is not a function at onClick in reactjs


I want to write context with UseReducer hook but an error error this:dispatch is not a function what is problem? please help me guys

almost is correct but not working it. I want to see the appropriate action by clicking on the buttons, one is increment, one is decrement and the other is reset.

CounterOne

import { UseCount, UseCountActions } from "./CounterProvider";

const CounterOne = () => {
  const count = UseCount();
  const dispatch = UseCountActions();
  return (
    <div>
      <h2>count is:{count}</h2>

      <button onClick={() => dispatch({ type: "add", value: 1 })}>
        Addone{" "}
      </button>
      <button onClick={() => dispatch({ type: "decrement", value: 1 })}>
        decrement
      </button>
      <button onClick={() => dispatch({ type: "reset" })}>reset</button>
    </div>
  );
};

export default CounterOne;

CounterProvider

import React, { useReducer, useState } from "react";
import { useContext } from "react";

const CounterContext = React.createContext();
const CounterContextDispather = React.createContext();

const initialState = 0;

const reducer = (state, action) => {
  switch (action.type) {
    case "add":
      return state + action.value;
    case "decrement":
      return state - action.value;
    case "reset":
      return initialState;
    default:
      return state;
  }
};

const CounterProvider = ({ children }) => {
  const [count, dispatch] = useReducer(reducer, initialState);
  return (
    <CounterContext.Provider value={count}>
      <CounterContextDispather.Provider value={dispatch}>
        {children}
      </CounterContextDispather.Provider>
    </CounterContext.Provider>
  );
};

export default CounterProvider;

export const UseCount = () => useContext(CounterContext);

export const UseCountActions = () => {
  return CounterContextDispather;
};

Solution

  • export const UseCountActions = () => {
      return useContext(CounterContextDispather);
    };
    

    There is a official example