Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

169
Vistas
How do I fetch the response from an apiCall to display in my component?

Basically I have my AuthContext, with my reducer, actions and apicalls.

AuthReducer:

        case "LOGIN_FAILURE":
        return {
            user: null,
            isFetching: false,
            error: true,
        };

AuthActions:

export const loginFailure = () => ({
type:"LOGIN_FAILURE",

});

ApiCalls:

export const login = async (user, dispatch) => {
dispatch(loginStart());
try {
    const res = await axios.post("/auth/login", user);
    dispatch(loginSuccess(res.data));
} catch (err) {
    dispatch(loginFailure());
}

};

and the actual call in my api:

router.post("/login", async (req, res) => {
    try {
        const user = await User.findOne({ email: req.body.email });
        !user && res.status(401).json("Wrong password or username!");

        const bytes = CryptoJS.AES.decrypt(user.password, process.env.SECRET_KEY);
        const originalPassword = bytes.toString(CryptoJS.enc.Utf8);

        originalPassword !== req.body.password &&
        res.status(401).json("Wrong password or username!");

        const accessToken = jwt.sign(
            { id: user._id, isAdmin: user.isAdmin },
            process.env.SECRET_KEY,
            { expiresIn: "5d" }
        );

        const { password, ...info } = user._doc;

        res.status(200).json({ ...info, accessToken });
    } catch (err) {
        res.status(500).json();

    }
});

and in my component:

    const handleLogin = (e) => {
    if(email.match(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/g)){
        login({email, password}, dispatch);
        e.preventDefault();
        history.push("/");
    }
};

Everything works wonderfully. Now when I enter the wrong login credentials, obviously nothing happens. In the chrome console under Network -> Response, I get my "Wrong Username or Password". But how do I fetch the 401 response to display it in my component, so I can display it over my login Button IF I enter the wrong login credentials.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I think you can try implementing the Toastify into your project, import it into the Log In component

import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

, whenever you get 401 condition, as I see in your code, around here:

const user = await User.findOne({ email: req.body.email });
!user && res.status(401).json("Wrong password or username!");

and here:

originalPassword !== req.body.password &&
res.status(401).json("Wrong password or username!");

just implement the toast.error('Your desire error') into it, you don't have to rework the code or anything so much and I think you're good to go.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda