0

I am trying to pull a recipe list from a server that is expecting an auth token from local storage. I created a local axiosWithAuth file because I am going to be hitting multiple endpoints from the API. My auth file looks like this...

 import axios from 'axios';

const axiosWithAuth = () => {
  const token = localStorage.getItem('token');

  return axios.create({
    baseURL: 'https://secret-fam-recipes.herokuapp.com/api',
    headers: { Authorization: token }
  });
};

export default axiosWithAuth

I am then using this axios call with Redux actions so that the data that is returned updates the store for my project. I have tried calling the API two different ways. One with async await which looks like this...

export const listRecipes = () => async (dispatch) => {
    dispatch({type: actions.FETCH_RECIPES_REQUEST});
    try {
        const {recipes} = await axiosWithAuth.get("/recipes")
        console.log("recipes", recipes)
        dispatch({type: actions.FETCH_RECIPES_SUCCESS, payload: recipes})
    } catch(error) {
        dispatch({type: actions.FETCH_RECIPES_FAILURE,
            payload:
                error.resposne && error.response.message
                ? error.response.message
                : error.message
            })
    }
}

and another without async await which looks like this...

export const listRecipes = () => (dispatch) => {
    dispatch({type: actions.FETCH_RECIPES_REQUEST});
    axiosWithAuth.get("/recipes")
    .then(data => {
        return dispatch({type: actions.FETCH_RECIPES_SUCCESS, payload: data})
    })
    .catch(error => {
        dispatch({type: actions.FETCH_RECIPES_FAILURE,
            payload:
                error.resposne && error.response.message
                ? error.response.message
                : error.message
            })
    })
}

I also imported my dependencies like so...

import axiosWithAuth from "../utils/axiosWithAuth";
import * as actions from "../constants/recipeConstants";

When I try the async await action I get a 500 error back from the server. When I use the non async await action I get a type error when trying to load the page that says the following..

TypeError: _utils_axiosWithAuth__WEBPACK_IMPORTED_MODULE_0__.default.get is not a function

so obviously there is something wrong with my actions or my axiosWithAuth format. I have tried changing my axiosWithAuth function to use the auth keyword instead of headers but it does not work still. I am not sure if my action is written improperly or if there is something else I should look at. Any help would be greatly appreciated. Thank you!

Alex Motor
  • 59
  • 8
  • Did you tried this API's from browser or postman, just wanted to sure that these API's are working – Learner Feb 05 '21 at 20:08
  • If the above works, try passing the headers directly so that we can sure if the below works https://stackoverflow.com/questions/44617825/passing-headers-with-axios-post-request, its basically with that axiosWithAuth. Let me know – Learner Feb 05 '21 at 20:09
  • Yes the API is working according to postman I just tried using a basic axios request and passed the token as a parameter for the action. I then called it from my React component with the token. That got the page to load successfully but React Dev tools shows the API call failed with a status code 404 – Alex Motor Feb 05 '21 at 21:58

2 Answers2

1

I was just working with someone and we figured it out. axiosWithAuth is a function so I should have called the function in my action. The correct line is

const {recipes} = await axiosWithAuth().get("/recipes")
Alex Motor
  • 59
  • 8
0

More short approach is not to return a function from your custom axios but return the actual axios instance. Since you're just setting a header, you can do this:

import axios from 'axios';

const axiosInstance = axios.create({
    baseURL: 'https://secret-fam-recipes.herokuapp.com/api'
});

axiosInstance.interceptors.request.use((config) => {
      config.headers['Authorization'] = localStorage.getItem('token');
      return config;
});

export default axiosInstance;

And then, just import and use the axios instance:

import axios from './custom-axios';

axios.get('/url-here');

Haseeb Anwar
  • 2,438
  • 19
  • 22