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

280
Visualizações
Custom context provider not able to return anything including basic html elements

I'm following this tutorial and am up to the part about implementing a custom AuthContext provider. Here is the suggested code:

const AuthProvider = ({ children }) => {
  const [token, setToken] = React.useState(null);

  const handleLogin = async () => {
    const token = await fakeAuth();

    setToken(token);
  };

  const handleLogout = () => {
    setToken(null);
  };

  const value = {
    token,
    onLogin: handleLogin,
    onLogout: handleLogout,
  };

  return (
    <AuthContext.Provider value={value}> // AuthContext defined right above component; initialised as an empty object.
      {children}
    </AuthContext.Provider>
  );
};

As far as I can tell, that's absolutely fine. But when I try adding it to my code (literally copy and paste it in) the return statement throws 9 errors. Cannot find namespace 'AuthContext'.ts(2503), '>' expected.ts(1005), Operator '<' cannot be applied to types 'boolean' and 'RegExp'.ts(2365) etc.

Even if I just try to return a div, I get Cannot find name 'div'.ts(2304).

What's preventing me from being able to return any elements in my return statement?

EDIT: Update to include my full code.

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

type AuthContextType = {
  token: string | undefined;
};

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

const fakeAuth = () =>
    new Promise((resolve: (arg0: string) => void) => {
      setTimeout(() => resolve("2342f2f1d131rf12"), 250);
    });

export const AuthProvider = ({ children }: {children: ReactNode}) => {
  const [token, setToken] = useState<string | undefined>();

  const handleLogin = async () => {
    const token = await fakeAuth();
    setToken(token);
  };

  const handleLogout = () => {
    setToken(undefined);
  };

  const value = {
    token,
    onLogin: handleLogin,
    onLogout: handleLogout,
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
};
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

In the example you shared the context is created like this before creating the provider

const AuthContext = React.createContext(null);

If you try something like below?

import React from "react";

const AuthContext = React.createContext(null);

const AuthProvider = ({ children }) => {
  const [token, setToken] = React.useState(null);

  const handleLogin = async () => {
    const token = await fakeAuth();

    setToken(token);
  };

  const handleLogout = () => {
    setToken(null);
  };

  const value = {
    token,
    onLogin: handleLogin,
    onLogout: handleLogout,
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
};
about 4 years ago · Juan Pablo Isaza Relatório

0

Check the file name, in my case it had a .ts extension and it was solved by changing to .tsx

import React, { useState, useEffect, createContext, ReactNode, Context } from 'react';

export type AuthContextType = {
  user?: boolean;
  isLoading?: boolean;
}

export const initialState: AuthContextType = {
  user: false,
  isLoading: true,
};

export interface AuthProviderProps {
  children?: ReactNode
}

export const AuthContext: Context<AuthContextType> = createContext<AuthContextType>(initialState);

const AuthCookieProvider: React.FC<AuthProviderProps> = ({ children }: AuthProviderProps): JSX.Element => {
    const [user, setUser] = useState<AuthContextType>(initialState);

    useEffect(() => {
        checkUserLogin(setUser);
    }, []);

    return <AuthContext.Provider value={user}>{children}</AuthContext.Provider>;
};

export default AuthCookieProvider;
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