Home > database >  TypeScript AuthContext cant take undefined when on Routes
TypeScript AuthContext cant take undefined when on Routes

Time:03-29

I'm using TypeScript and I need to create a route with the user info and sign with google from firebase (I plan to switch to Redux as an exercise later).

Happens that when typing the user, if its logged in = User, if its not = undefined, but Router won't take an undefined as a child...

import { createContext, useState } from "react";
import { BrowserRouter, Route, Routes } from "react-router-dom";

import { auth, firebase } from "./services/firebase";

import { Home } from "./pages/Home";
import { NewRoom } from "./pages/NewRoom";

type User = {
  id: string;
  name: string;
  avatar: string;
};

type AuthContextType = {
  user: User | undefined;
  signInWithGoogle: () => Promise<void>;
};

export const AuthContext = createContext({} as AuthContextType);

function App() {
  const [user, setUser] = useState<User>();

  async function signInWithGoogle() {
    // provider is whos giving the log in - google
    const provider = new firebase.auth.GoogleAuthProvider();

    const result = await auth.signInWithPopup(provider);

    if (result.user) {
      // username, photoLocation, uniqueID
      const { displayName, photoURL, uid } = result.user;

      // what if theres no data?
      if (!displayName || !photoURL)
        throw new Error("Missing information from Google Account");

      // set user information
      setUser({
        id: uid,
        name: displayName,
        avatar: photoURL,
      });
    }
  }

  return (
    <BrowserRouter>
      <Routes>
        <AuthContext.Provider value={{ user, signInWithGoogle }}>
          <Route path="/" element={<Home />} />
          <Route path="/room/new" element={<NewRoom />} />
        </AuthContext.Provider>
      </Routes>
    </BrowserRouter>
  );
}

export default App;

CodePudding user response:

Whenever you want to render nothing, use null instead of undefined. If User is not not logged in, you can redirect to an unauthorized page using <Navigate to="/signin" /> which is a valid child for router (just a suggestion).

CodePudding user response:

Sorry, it was late and past my bed time, it was a simple fix:

before: `return (

  <Routes>
    <AuthContext.Provider value={{ user, signInWithGoogle }}>
      <Route path="/" element={<Home />} />
      <Route path="/room/new" element={<NewRoom />} />
    </AuthContext.Provider>
  </Routes>
</BrowserRouter> 

after:

`` return (

<BrowserRouter>
  <AuthContext.Provider value={{ user, signInWithGoogle }}>
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/room/new" element={<NewRoom />} />
    </Routes>
  </AuthContext.Provider>
</BrowserRouter>

); ``

Just move AuthContext out of Routes as it is not a Route, obviously

  • Related