i am trying save user object in context but i am gettin g undefined this is my context:
import { createContext } from "react";
export const UserContext = createContext(null)
this is routs :
import { UserContext } from './contexts/UserContext.js';
const [user, setUser] = useState();
<UserContext.Provider value={{user:user , setUser:setUser}}>
<Routes>
<Route path="/login" exact element={ <Login />} />
<Route path="/numberinput" exact element={<NumberInput />} />
<Route path="/VerifyPhone" exact element={<VerifyPhone />} />
<Route path="/Register" exact element={<Register />} />
<Route path="/ChangePassword" exact element={<ChangePassword />} />
<Route path="/" exact element={<PrivateRoute><Home /></PrivateRoute>} />
{/* <Route path="/Answers" exact element={<Answers />} />
<Route path="/results/:id/:quizzes_id" exact element={<Results />} /> */}
<Route path="/payment" element={<PrivateRoute><Payment /></PrivateRoute>} />
<Route path="/*" element={<FourOFour />} />
</Routes>
</UserContext.Provider>
and this is how i want to store data in another file:
import { UserContext } from '../../contexts/UserContext.js';
const { setUser } = useContext(UserContext);
baseUrl
.post('api/v1/login', data)
.then((response) => {
setUser(response.data.data);
console.log(response.data.data);
Swal.fire({
icon: 'success',
title: response.data.data.message,
showConfirmButton: false,
timer: 1000,
}).then(() => {
window.location.pathname = '/';
});
})
and when i log the user in '/' rout i am getting undefiend
CodePudding user response:
You forgot to add an initial value to the useState
hook.
const [user, setUser] = useState(null);
And,
Don't use only a console.log() to log the user as it runs only once when your App mounts.
Do this instead to log the user every time it changes:
// state
const [user, setUser] = useState(null);
// log user every time it changes
useEffect(()=> {
console.log(user, "user from effect hook")
}, [user])
Set user in Login component
import React from "react";
// import UserContext correctly
import { UserContext } from "<path-to-UserContext>";
export default function Login() {
const { user, setUser } = useContext(UserContext);
// set the user
useEffect(() => {
setUser("something");
}, []);
return <></>;
}
Note: I'm assuming that you are getting the data from API correctly.
CodePudding user response:
You should initialize properties of the context in first parameter of the createContext function as follows,
const userContext = createContext({ user: null, setUser: () => {} })