Uncaught (in promise) TypeError: dispatch is not a function useContext/useReducer

shivam chawla

I am new to react. I am working on a blogging website in which I need to create a login page. I am facing the following error: TypeError: dispatch is not a function

Following is my code to handle submit and request to the API. I am getting ...

const { dispatch, isFetching } = useContext(Context);
const handleSubmit = async (e) => {
    e.preventDefault();
    dispatch({ type: "LOGIN_START" });
    try {
      const res = await axios.post("http://localhost:5001/api/auth/login", {
        username: userRef.current.value,
        password: passwordRef.current.value,
      });
      dispatch({ type: "LOGIN_SUCCESS", payload: res.data });
    } catch (err) {
      dispatch({ type: "LOGIN_FAILURE" });
    }
  };

...

Following is my code of the form:

...

return (
    <div className="login">
      <span className="loginTitle">Login</span>
      <form className="loginForm" onSubmit={(e) => handleSubmit(e)}>
        <label>Username</label>
        <input
          type="text"
          className="loginInput"
          placeholder="Enter your username..."
          ref={userRef}
        />
        <label>Password</label>
        <input
          type="password"
          className="loginInput"
          placeholder="Enter your password..."
          ref={passwordRef}
        />
        <button className="loginButton" type="submit" disabled={isFetching}>
          Login
        </button>
      </form>
      <button className="loginRegisterButton">
        <Link className="link" to="/register">
          Register
        </Link>
      </button>
    </div>
  );

...

Following is the Context Provider

...

import { createContext, useEffect, useReducer } from "react";
import Reducer from "./Reducer";

const INITIAL_STATE = {
  user: JSON.parse(localStorage.getItem("user")) || null,
  isFetching: false,
  error: false,
};

export const Context = createContext(INITIAL_STATE);

export const ContextProvider = ({ children }) => {
  const [state, dispatch] = useReducer(Reducer, INITIAL_STATE);

  useEffect(() => {
    localStorage.setItem("user", JSON.stringify(state.user));
  }, [state.user]);

  return (
    <Context.Provider
      value={{
        user: state.user,
        isFetching: state.isFetching,
        error: state.error,
        dispatch,
      }}
    >
      {children}
    </Context.Provider>
  );
};

...

Following is my app.js with all the root nodes in it ...

import Home from "./Pages/home/Home";
import TopBar from "./components/topbar/TopBar";
import Single from "./Pages/single/Single";
import Write from "./Pages/write/Write";
import Settings from "./Pages/settings/Settings";
import Login from "./Pages/login/Login";
import Register from "./Pages/register/Register";
import { useContext } from "react";
import { Context } from "./context/Context";
import {
  BrowserRouter as Router,
  Routes,
  Route,
  Link,
  BrowserRouter
} from "react-router-dom"

function App() {
  const { user } = useContext(Context);
  return (
    <BrowserRouter >
      <TopBar />
      <Routes>
        <Route exact path="/" element={<Home />} />
        <Route path="register" element={user ? <Home /> : <Register />} />
        <Route path="login" element={ user ? <Home /> : <Login />} />
        <Route path="write" element={user ? <Write /> : <Register />} />
        <Route path="settings" element={user ? <Settings /> : <Register />} />
        <Route path="post/:postId" element={<Single />} />
      </Routes>
    </BrowserRouter >
  );
}

export default App;

...

Can somebody please help me out with this.

Nicholas Tower

You are apparently getting the default value from the context, and your default value does not have a dispatch function. For context to work, there must be a context provider higher up the component tree than the component that's trying to consume context.

You are either not rendering a ContextProvider at all, or you are rendering it in the wrong part of the component tree.

For example, the following will work:

const App = () => {
  return (
    <ContextProvider>
      <MyForm />
    <ContextProvider>
  ) 
}

const MyForm = () => {
  const { dispatch, isFetching } = useContext(Context);
  const handleSubmit = async (e) => {
     // ...
  }

  return (
    <div className="login">
      // ...
    </div>
  )
}

But this will not (the provider is a child of the consumer):

const MyForm = () => {
  const { dispatch, isFetching } = useContext(Context);
  const handleSubmit = async (e) => {
     // ...
  }

  return (
    <ContextProvider>
      <div className="login">
        // ...
      </div>
    </ContextProvider>
  )
}

And neither will this (the provider exists, but isn't an ancestor of MyForm)

const App = () => {
  return (
    <div>
      <MyForm />
      <ContextProvider />
    </div>
  )
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Uncaught TypeError: dispatch(...).then is not a function

Uncaught TypeError: dispatch is not a function

Uncaught (in promise) TypeError: $ is not a function

Uncaught (in promise) TypeError: spawn is not a function

Uncaught (in promise) TypeError: X is not a function

Uncaught (in promise) TypeError: this.~(...).then is not a function

Uncaught (in promise) TypeError: setExercises is not a function

Uncaught TypeError: this.props.dispatch is not a function

Uncaught (in promise) TypeError: Cannot read property 'dispatch' of undefined

Uncaught (in promise) TypeError: response.json is not a function

Uncaught (in promise) TypeError: Cannot call a class as a function

Uncaught (in promise) TypeError: localStorage.setItem is not a function

Uncaught (in promise): TypeError: component.canDeactivate is not a function

redux-promise: Uncaught TypeError: middleware is not a function

Angular : Error: Uncaught (in promise): TypeError: Object(...) is not a function

Error: Uncaught (in promise): TypeError: guard is not a function

Uncaught (in promise) TypeError: (intermediate value).setAttribute is not a function

Uncaught (in promise) TypeError: mostrarError is not a function. with hooks

Uncaught (in promise) TypeError: images.map is not a function

Uncaught (in promise) TypeError: type.trim is not a function

Uncaught (in promise) TypeError: this.loadCategories is not a function in React

Uncaught (in promise) TypeError: video.addEventListner is not a function

Uncaught (in promise) TypeError: img.src is not a function

Uncaught (in promise) TypeError: viewer.loadExtensionAsync is not a function

Uncaught Error: Uncaught (in promise): TypeError: this.xxxService.getSomething(...).toPromise is not a function

lodash throttle redux dispatch Uncaught TypeError: Expected a function

How can i fix "Uncaught TypeError: dispatch is not a function"?

React Redux, Uncaught TypeError: this.props.dispatch is not a function, when trying to dispatch a form submit?

I keep getting " Uncaught TypeError: dispatch is not a function" whenever I try to use dispatch using useContext hook