1

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

saeed
  • 69
  • 1
  • 9

2 Answers2

1

You should initialize properties of the context in first parameter of the createContext function as follows,

    const userContext = createContext({ user: null, setUser: () => {} })
Shakya Peiris
  • 504
  • 5
  • 11
  • its not undefined now it is null the setUser doesn't work i think – saeed May 14 '22 at 05:37
  • That's because you're logging it olnly on component mount. You need an useEffect hook to look for changes in user state. – Amit May 14 '22 at 05:41
  • but when i change the user to a static string value it logs the string – saeed May 14 '22 at 05:42
  • Then either you're not getting data from API. Or maybe you're not setting it correctly. Try to check the network tab in Chrome Dev Tools. – Amit May 14 '22 at 05:45
  • i am getting user from api corrctly i checked it – saeed May 14 '22 at 05:48
1

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.

Amit
  • 1,018
  • 1
  • 8
  • 23
  • yes i am getting data from api and its correct i log the user in useEffect but still it is null i think setUser doesn't work – saeed May 14 '22 at 05:40
  • @saeed It should be null for the first time. When setUser is invoked, you should get another log with the updated value of user. – Amit May 14 '22 at 05:43
  • useEffect(()=>{ setUser({...user , log:'ll'}) console.log(user); },[user]) i did this but still there is no user – saeed May 14 '22 at 05:47
  • @saeed Don't **setUser** in a useEffect call where **user** itself is a dependecy. This results in too many re-renders. Just log the user in useEffect. Use another useEffect in App.js or any other child component to set the user. – Amit May 14 '22 at 05:50
  • Take a look at the updated answer. I hope you can troubleshoot it now. Or, you need to add complete code for **App** and **Login** components (don't make it too long) along with directory structure. – Amit May 14 '22 at 05:59
  • i don't get it the useEffect after some rerender should show the user i set the user in a login page and in dashboard in useEffect i logged it – saeed May 14 '22 at 05:59
  • sorry i mean home component – saeed May 14 '22 at 06:07
  • thank you @Amit the updated answer doesn't work – saeed May 14 '22 at 06:08
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/244734/discussion-between-amit-and-saeed). – Amit May 14 '22 at 06:09
  • 1
    window.location.pathname = '/'; this was the problem changed it to navigate and problem solved – saeed May 14 '22 at 07:07