4

I'm trying to learn React & context.

In the following example, I have my console log correctly the user (which is currently set) in app.js, but in the RequireAuth component (and in its child) logs undefined.

I could probably pass user & setUser as props and have them working, but the goal is to understand what's going wrong and learn how to use context correctly.

Thanks for the help!

userContext.js

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

const UserContext = createContext();

export function useAuth() {
    return useContext(UserContext);
}

const UserProvider = ({ children }) => {
    const [state, setState] = useState(undefined);

    return (
        <UserContext.Provider value={[state, setState]}>
            { children }
        </UserContext.Provider>
    );
}

export default UserProvider;

app.js

import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

// Components
// [...]

// Auth Components
import RequireAuth from './requireAuth';

// Context
import UserProvider from './userContext';
import { useAuth } from './userContext';

function App() {

  return (
    <Router>
      <UserProvider>
        <Main />
      </UserProvider>
    </Router>
  );
}

function Main() {
  const [ user, setUser ] = useAuth();
  console.log(user) // LOGS USER
  return (
    <div className="App">
      <Navbar />
      <Title />
      <Routes>
        <Route
          path="/home"
          element={ 
            <RequireAuth>
              <Home />
            </RequireAuth> 
          } />
      </Routes>
      <Footer />
    </div>
  )
}

export default App;

requireAuth.js

import React from 'react';
import { useAuth } from './userContext';


const RequireAuth = ({ children }) => {
    const [ user, setUser ] = useAuth();
    console.log(user) // LOGS UNDEFINED
    
    /* Some logic running if user is set or not */

    return children;
}

export default RequireAuth;
lytonist
  • 53
  • 6
  • Are you able to maybe create a [mre] so that we can help debug the issue, there are some tools online to help with that for react apps such as [codesandbox](https://codesandbox.io/dashboard/home?workspace=3540bb7d-da28-4d1f-84d0-fae3f9183abe). – Nick Parsons Dec 07 '21 at 11:26
  • 1
    Thanks for your comment. I created a codesandbox and everything was working fine there. So it helped me understand the problem was elsewhere. – lytonist Dec 07 '21 at 14:12

1 Answers1

1

Found what was wrong. My problem was that I didn't use correctly router Links and every time context was reset. The shown code, after setting up the proper Links, works fine.

lytonist
  • 53
  • 6