0

I'm creating RN app with redux (+thunk+persistant) and axios (+ interceptor for refreshing token) for API calls.

I organized my app logic as separate files with actions combaining with axios API calls (because it is very clear for me) and reducers in diferent files.

And problem is with refresh tokens witch should be handled in action files.

For example simple actions file "projects.js":

import createAuthRefreshInterceptor from 'axios-auth-refresh';
import axios from 'axios';


const refreshAuthLogic = failedRequest => axios.post('http://domain.pl/api/refresh-token').then(tokenRefreshResponse => {

    // >>>> save token to persistant part of REDUX ?????

    failedRequest.response.config.headers['Authorization'] = 'Bearer ' + // >>>> get token from persistant part of REDUX ?????;
    return Promise.resolve();
});


/*
 * action types
 */
export const FETCH_PROJECTS = 'FETCH_PROJECTS'


/*
 * API URL & config
 */
const apiUrl = 'http://domain.pl/api/projects';



/*
 * action creators
 */


export const fetchProjects = () => {
  return (dispatch, getState) => {
    const state = getState();
    createAuthRefreshInterceptor(axios, refreshAuthLogic);
    return axios.get(apiUrl, {headers: {'Authorization': "bearer " + state.auth.user.access_token }})
      .then(response => {

        dispatch(fetchProjectsSuccess(response.data))
      })
      .catch(error => {
        throw(error);
      });
  };
};

export const fetchProjectsSuccess =  (projects) => {
  return {
    type: FETCH_PROJECTS,
    projects: projects
  }
};

I'm trying do this like below but always get some errors. Accessing Redux state in an action creator?

What is the best way to handling access/refresh tokens in action file (axios+redux)?

thank you!

1 Answers1

1

I'd separate the token refresh logic and the redux actions entirely. There's no need for the redux world to be concerned with how an api client handles its authentication header. Try this:

  1. Don't expose axios directly in your action creator module.
  2. Instead, move the pure request logic into a separate module where an axios instance is created once and used for all request.
  3. You can attach response interceptors to this client instance that automatically handle the token refresh.
  4. Export a method called getProjects that is imported by the action creator module.
  5. Use getProjects in your thunk action fetchProjects without being concerned with authentication, simply leave this part to the api client.
timotgl
  • 2,865
  • 1
  • 9
  • 19