yield axios.get() call in Saga changes the pathname to the default location "/"

1.3k views Asked by At

I have have this Saga for retrieving the token from localStorage and sign in the user automatically

export function* authCheckState(action) {
    const token = localStorage.getItem("jwt");
    const expDate = localStorage.getItem("expDate");
    if (!token) {
        yield put(actions.logout()); 
    } else {
        const expirationDate = new Date(expDate);
        if (expirationDate <= new Date()) {
            yield put(actions.logout());
        } else {
            axios.defaults.headers.common['Authorization'] = token;
            const username = localStorage.getItem('username');
            // const loggedInUser = yield axios.get(`/users/${username}`);
            // console.log('HERE');
            yield put(actions.loginSuccess());
            yield put(
                actions.fireTimeout(
                    (expirationDate.getTime() - new Date().getTime())
                    // 10 * 1000 // ms
                )
            );
        }

    }
}

So If I visit any path in the application for example '/users' it stays the same after executing the saga.

now the code above as is is working perfectly. However now I want to add an axios call to get some data like this:

const loggedInUser = yield axios.get(`/users/${username}`);
// store it in the store.

When I add this axios call. I get redirected to the home page "/".

Before: working

enter image description here

After: not working redirection happens

enter image description here

2

There are 2 answers

0
usertest On BEST ANSWER

Funny, I changed the order of the call and now it's working properly!!

yield put(actions.loginSuccess());
const loggedInUser = yield axios.get(`/users/${username}`);
yield put(actions.loginSuccess(username, loggedInUser.data));
0
prince On

I wanted to comment but could not due to less points, may be you should use

yield call (Api.fetchUser,username)

where Api.fetchUser is a function which internally hits the rest api and returns a promise.