Home > other >  React async await not working with function component
React async await not working with function component

Time:12-31

Service class method:

logInUser = (model) => {

        fetch(this.urlService.authUrl, {
            method: 'POST',
            body: model,
            headers: { 'Content-Type': 'application/json' },
        }).then((res) => { return res.json() })
            .then((data) => {
                console.log(data);
                return data;
            });
    }

I am trying to above method from a reach component like below,

const handleFormSubmit = (e) => {
        e.preventDefault();
        login(e);
    };

login function in component look like,

const login = async (e) => {
        const data = await auth.logInUser(JSON.stringify({
            user_name: e.target.elements.user_name?.value,
            password: e.target.elements.password?.value,
        }));
        if (data?.status) {
            sessionStorage.setItem("logged_in_user_X_token", data?.data?.token);
            history.push("/dashboard");
        }
        else {
            debugger;
            setModalHeader(data?.message ?? "authentication_failed");
            setModalBody(data?.data ?? "invalid_credentials");
            setShowModal(true);
        }
    }

but here data always showing null and going to else part but when i am debugging the code i can see it's returning data from logInUser method.

CodePudding user response:

You have forgotten to return the Promise in logInUser. That's why the output of await auth.logInUser(..) is undefined.

logInUser = model => {
    return fetch(this.urlService.authUrl, {
        method: "POST",
        body: model,
        headers: { "Content-Type": "application/json" }
    })
        .then(res => {
            return res.json();
        })
        .then(data => {
            console.log(data);
            return data;
        });
};
  • Related