Hi,
I am using the Auth0 React SDK for my React + Redux app and having trouble figuring out how to use the getAccessTokenSilently() call to send the token with an external api call within the context of redux actions. Has anyone had success setting up a viable pattern here?
Note, with the below pattern, grabbing the token on button click is easy. My issue is with async calls such as when a component is mounted. Thanks in advance!
For reference, here is the basic setup of my app. It seems like the token could be grabbed from the SDK in either the global config (api.js) or where the action is defined (ie ProductActions) but neither of these are functional react components.
// api.js import axios from 'axios'; import { normalize } from 'normalizr'; import * as schema from './schema'; import { getApiDomain, getApiProtocol } from './shared/Shared'; // Configure Axios let domain = getApiDomain(); let protocol = getApiProtocol(); axios.defaults.baseURL = `${protocol}://${domain}/api/v1`; ... // Create axios instance export const ApiService = axios.create(); // API Calls export const getProducts = ( token ) => ApiService.get(`/products`, { headers: { Authorization: `Bearer ${token}` } }).then(normalizeProducts);
// ProductActions.js import * as api from '../Api'; const ACTIONS = { ... }; export const getProducts = (token) => (dispatch, getState) => { // Let the state know the submit is in progress dispatch({ type: ACTIONS.GET_PRODUCTS_SUBMITTING }); // Call the api, returns a promise return api.getProducts(token) .then((response) => { dispatch({ type: ACTIONS.GET_PRODUCTS_SUCCESS, response }); return response; }) .catch((error) => { var message = error.response ? error.response.data.error : error.message; dispatch({ type: ACTIONS.GET_PRODUCTS_FAILURE, message }) }); }; export default ACTIONS;