Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
TypeScript AuthContext cant take undefined when on Routes

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;

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda