简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM