Search code examples
reactjsreact-routeraxiosconnected-react-router

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


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


Solution

  • 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));