1

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.

1
  • what do you get if you console.log data inside your async login function? Before checking the status of data. Commented Dec 31, 2021 at 9:58

1 Answer 1

1

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;
        });
};
Sign up to request clarification or add additional context in comments.

1 Comment

@A_Sk, check this out !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.