Home > front end >  Why Data is null? React Redux
Why Data is null? React Redux

Time:01-13

Why Data is null? React Redux. This is my first time using Redux.

This is my request. The request works well. Status is 200 and request return me data

const API_URL = "http://URL/";

class AuthService {
    static async onHandleSignIn(login: string, password: string) {
        await fetch(API_URL   'api/Auth/signIn', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                'login': login,
                'password': password
            })
        }).then(response =>
            response.json().then(data => ({
                data: data,
                status: response.status
            })).then(res => {
                if (res.status === 200) {
                    localStorage.setItem('token', res.data.token);
                    return res.data
                }
            })
        )
    }
}

export default AuthService;

I try to get data in another method, they return undefined. The console shows that the data is undefined.

import AuthService from "../../../api/requests/authorization";

export const login = (username: string, password: string) => (dispatch: any) => {
    return AuthService.onHandleSignIn(username, password).then(
        (data) => {
            console.log(data) //data = undefined

            dispatch({
                type: "LOGIN_SUCCESS",
                payload: {user: data},
            });

            return Promise.resolve();
        },
        (error) => {
            dispatch({
                type: "LOGIN_FAIL",
            });

            console.log(error)

            return Promise.reject();
        }
    );
};

As I said, this is my first encounter with Redux. I will be glad for any help. TY)

CodePudding user response:

Try the following, you need to return the await fetch...

class AuthService {
    static async onHandleSignIn(login: string, password: string) {
        return await fetch(API_URL   'api/Auth/signIn', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                'login': login,
                'password': password
            })
        }).then(response =>
            response.json().then(data => ({
                data: data,
                status: response.status
            })).then(res => {
                if (res.status === 200) {
                    localStorage.setItem('token', res.data.token);
                    return res.data
                }
            })
        )
    }
}

export default AuthService;
  •  Tags:  
  • Related