Async/await not working in React typescript (Hooks)

Asked

Viewed 23 times

-2

I’m running a route-fed authentication. But this not respecting the await of the post in the login api. Sometimes it works locally but most of the time it "skips" the post.

import React, {useState} from 'react';
import logoImg from '../../assets/logo.svg';
import Input from '../../components/Input';
import Button from '../../components/Button';

import { useAuth } from '../../hooks/auth';

import {
    Container,
    Logo,
    Form,
    FormTitle,
} from './styles';

const SignIn: React.FC = () => {
    const [email, setEmail] = useState<string>('');
    const [password, setPassword] = useState<string>('');    
    
    const { signIn } = useAuth();

    return (
        <Container>
            <Logo>
                <img src={logoImg} alt="Minha Carteira" />
                <h2>Minha Carteira</h2>
            </Logo>

            <Form onSubmit={() => signIn(email, password)}>
                <FormTitle>Entrar</FormTitle>

                <Input 
                    type="email"
                    placeholder="e-mail"
                    required
                    onChange={(e) => setEmail(e.target.value)}
                />
                <Input 
                    type="password"
                    placeholder="senha"
                    required
                    onChange={(e) => setPassword(e.target.value)}
                />

               <Button type="submit">Acessar</Button>
            </Form>
        </Container>
    );
}

export default SignIn;

And auth.tsk:

import axios from 'axios';
import React, { createContext, useState, useContext, useMemo } from 'react';
import { URL_API } from '../repositories/baseAPI';

interface IAuthContext {
    logged: boolean;
    signIn(email: string, password: string): void;
    signOut(): void;
}

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

const AuthProvider: React.FC = ({ children }) => {
    const [logged, setLogged] = useState<boolean>(() => {
        const isLogged = localStorage.getItem('@minha-carteira:logged');

        return !!isLogged;
    });
    const [token, setToken] = useState<string>();
    const [idUsuario, setIdUsuario] = useState<string>();
    const [apelido, setApelido] = useState<string>();

    async function login(email: string, password: string) {
        return await axios.post(URL_API + '/login', {
            email: email,
            senha: password,
        });
    }

    const signIn = async (email: string, password: string) => {
        const { data } =  await login (email, password)
        setToken(JSON.parse(data)[0].Token)
        setIdUsuario(JSON.parse(data)[0].idUsuario)
        setApelido(JSON.parse(data)[0].Apelido)      
        
        if(token !== undefined){
            localStorage.setItem('@minha-carteira:logged', 'true');
            localStorage.setItem('@minha-carteira:usuarioId', idUsuario!);
            localStorage.setItem('@minha-carteira:nomeUsuario', apelido!);
            localStorage.setItem('@minha-carteira:token', token!);
            setLogged(true);
        }   
    }

    const signOut = () => {
        localStorage.removeItem('@minha-carteira:logged');
        localStorage.removeItem('@minha-carteira:usuarioId');
        localStorage.removeItem('@minha-carteira:nomeUsuario');
        localStorage.removeItem('@minha-carteira:token');
        setLogged(false);
    }

    return (
        <AuthContext.Provider value={{logged, signIn, signOut}}>
            {children}
        </AuthContext.Provider>
    );
}

function useAuth(): IAuthContext {
    const context = useContext(AuthContext);

    return context;
}

export { AuthProvider, useAuth };
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.