svrcekmichal / redux-axios-middleware

Redux middleware for fetching data with axios HTTP client
MIT License
918 stars 96 forks source link

set token #72

Closed Melvin-88 closed 7 years ago

Melvin-88 commented 7 years ago

I'm using your middleware. But, when I use the action it does not work, says no token:

import axios from "axios";
import Cookie from "js-cookie";
import { API_BASE_URL } from '../config';

let token = Cookie.get('token') ? Cookie.get('token') : '';

export const api = axios.create({
    baseURL: API_BASE_URL,
    headers: {'Authorization': token}
});

export default api;

action:

export function userInfo() {
    return {
        type: types.USER_INFO,
        payload: {
            request: {
                url: `/user-info/`,
                method: "get"
            }
        }
    };
}

in the login component I put the Cookie and go to the main page:

Cookie.set('token', 'Token '+ response.payload.data.token);
 this.context.router.history.push('/');

And already on the main page do not work action. I can see Cookies in Aplication -> Cookies. Only after rebooting the page everything works.

Can have to restart middleware config? Thanks :)

nmaves commented 7 years ago

I would look at the example for using interceptors. My guess is that you are creating your axios client long before you get the token back. Personally, I would store that token in your redux state and then use it in a request interceptor.

Melvin-88 commented 7 years ago

nmaves Could you show how to do it?

nmaves commented 7 years ago

https://github.com/svrcekmichal/redux-axios-middleware#interceptors

Melvin-88 commented 7 years ago

Thanks a lot, it solved my problem.

nmaves commented 7 years ago

No problem!