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!