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.
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>
)
}