axios.create' is undefined - react-native

I am implementing axios interceptor in tsx for react native expo. I am geting following error:
TypeError: axios.create is not a function. (In 'axios
.create()', 'axios.create' is undefined).
How can I solve this?
Version for axios: "axios": "^1.2.1",
import { _retrieveData } from "./AsyncStorage";
const configData = require('../config/config.json');
const axios = require('axios');
const userApi = axios.create();
userApi.defaults.timeout = 4000;
userApi.interceptors.request.use(async (config: any) => {
const token = await _retrieveData('token');
config.headers.common = { 'Authorization': `Bearer ${token}` }
return config;
}, (error: any) => {
return Promise.reject(error);
});
export default userApi;

Related

Mock .get() Function using Jest on VueJS

I am trying to mock a GET request to get some Posts using the ID. This is the code I am trying to mock:
getPost() {
this.refreshToken();
http
.get(`/posts/${this.$cookie.get('postid')}`, {
headers: {
"Authorization": `Bearer ${this.$cookie.get('token')}`,
"Content-type": "application/json",
},
})
.then((response) => {
this.post = response.data;
})
.catch((error) => {
console.log(error.response);
});
}
This is my attempt at a test:
import {getPost} from '#/views/Post.vue'
import axios from 'axios';
jest.mock('axios');
describe('get Post by ID', () => {
afterEach(() => {
jest.resetAllMocks();
});
it('should return empty when axios.get failed', async () => {
const getError = new Error('error');
axios.get = jest.fn().mockRejectedValue(getError);
const actualValue = await getPost();
expect(actualValue).toEqual(new Map());
expect(axios.get).toBeCalledWith('/posts/postid');
});
it('should return users', async () => {
const mockedUsers = [{ postID: 1 }];
axios.get = jest.fn().mockResolvedValue(mockedUsers);
const actualValue = await getPost(['1']);
expect(actualValue).toEqual(mockedUsers);
expect(axios.get).toBeCalledWith('/posts/postid');
});
})
The error I am getting is:
TypeError: (0 , _Post.getPost) is not a function
I am not sure what to do, and any help would be super appreciated. Thanks!
Assuming you have getPost() defined in the Post component's methods, you can't use named imports to access getPost. Instead, you'll have to mount the component, and use the wrapper's vm:
// Post.spec.js
import { shallowMount } from '#vue/test-utils'
import Post from '#/views/Post.vue'
it('...', () => {
const wrapper = shallowMount(Post)
await wrapper.vm.getPost()
expect(wrapper.vm.post).toEqual(...)
})
Also make sure to return the axios call in getPost() so that it could be awaited:
// Post.vue
export default {
methods: {
getPost() {
this.refreshToken();
👇
return http.get(/*...*/)
.then(/*...*/)
.catch(/*...*/);
}
}
}

axios cancel is not working in react native redux

I am using axios for api call in react native application. I have redux for managing state in the application. I am trying to cancel the axios request when the component is unmounted but it is not cancelling.
import axiosMaker from '../../axios'
useEffect(() => {
const source = axios.CancelToken.source()
props.fetchFile(fileName, source.token)
return() => {
console.log('un mounting document view')
source.cancel()
}
},[])
//redux action
export const fetchFile = (location, token) => {
return async (dispatch) => {
dispatch(fetchFileRequest())
const config = {
path : location,
}
let axiosObj = await axiosMaker()
try{
axiosObj.post('download', config,
{
headers :{
'authorization' : `Bearer ${accessToken}`
}
},
{
cancelToken: token
}
)
.then(async response => {
console.log('doucment view success')
dispatch(fetchFileSuccess(response.data))
})
.catch(error => {
console.log('doucment view failure')
dispatch(fetchFileFailure(error))
})
} catch(error){
if(axiosObj.isCancel(error)){
console.log('request is canceled')
}
console.log('hello world')
}
}
}
What am I doing wrong here? How to cancel the axios call in redux?
I was sending accessToken and cancelToken separately. I sent it together.
axiosObj.post('download', config,
{
headers :{
'authorization' : `Bearer ${accessToken}`
},
cancelToken : token
}
)
and another changes is isCancel() function is available in the axios object itself not in the customize axios object. So, I imported the axios
import axios from 'axios'
and called isCancel function in this object, not in the axiosMaker object.
if(axios.isCancel(error)){
console.log('request is canceled')
}

Redux, Axios, and Redux Thunk with Expo 37

so i am using Redux redux-thunk redux-persist and axios all together here is my setup:
**action.js**
import axios from 'axios';
import * as type from './constants';
export const handleSignup = userDetails => async (dispatch) => {
const {
email, password, username, version,
} = userDetails;
return axios
.post('/users/signup', {
email,
password,
username,
platform: version,
})
.then((res) => {
dispatch({
type: type.USER_SIGNUP_SUCCESS,
payload: res.data,
});
axios.defaults.headers.common.Authorization = `Bearer ${
res.data.access_token
}`;
return res;
});
};
**api.js**
import axios from 'axios';
import configureStore from '../store/configureStore';
const { store } = configureStore();
axios.defaults.baseURL = 'http://baseurl/api/v1';
axios.defaults.headers.common['Content-Type'] = 'application/json';
const accesToken = store.getState().authentication.token;
if (accesToken) {
axios.defaults.headers.common.Authorization = `Bearer ${accesToken}`;
}
axios.defaults.headers.common['Content-Type'] = 'application/json';
axios.interceptors.response.use(
async response => response,
error => Promise.reject(error),
);
**configureStore.js**
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';
import { persistStore, persistCombineReducers } from 'redux-persist';
import rootReducer from '../reducers';
import storage from 'redux-persist/lib/storage';
const persistConfig = {
key: 'root',
storage,
blacklist: ['name1', 'name2', 'name3'],
};
const middlewares = [thunk];
const enhancer = composeWithDevTools(applyMiddleware(...middlewares));
const persistedReducer = persistCombineReducers(persistConfig, rootReducer);
export default () => {
const store = createStore(persistedReducer, undefined, enhancer);
const persistor = persistStore(store, null, () => {
store.getState();
});
return { store, persistor };
};
and i got this code inside my reducer for the signup success action
case type.USER_SIGNUP_SUCCESS:
return {
...state,
...action.payload.data.user,
email: action.payload.data.user.email,
username: action.payload.data.user.username,
token: action.payload.data.access_token,
user_id: action.payload.data.user.id,
};
and finally, i am calling handleSignUp on a submit button click:
onSignupClicked = () => {
this.setState({
error: false,
errorMessage: [],
loading: true,
});
const { platform } = Constants;
const version = Object.keys(platform)[0];
const {
user: { email, password, username },
} = this.state;
const { handleSignup, navigation } = this.props;
handleSignup({
email,
password,
username,
version,
})
.then(() => {
this.setState({ loading: true });
navigation.navigate(NAV_INTRO);
})
.catch((err) => {
console.log('ERROR : ',err)
});
};
sorry for a long code, so now my problem is that as soon as the user presses signup i am automatically getting ERROR : Network Error message. it doesn't wait for the request to get completed i guess, but the confusing part for me is this same code works on a previous version of the app with Expo 30.0.0, now its running on Expo 37.0.0. and i have double checked the API no problem with that, my question is is there something wrong with his code? is there a reason for it to return Network Error so fast?
i know this is bulky but any suggestion would be nice, Thanks.
in case its important here are my versions:
"react-redux": "5.0.7",
"redux": "4.0.0",
"redux-devtools-extension": "^2.13.8",
"redux-logger": "3.0.6",
"redux-mock-store": "1.5.3",
"redux-persist": "5.10.0",
"redux-thunk": "2.2.0",

Facing some issues while creating axios interceptor in react native

I am creating an app in react native and using laravel as backend. To manage error globally i am trying to create a axios request interceptor (never create before) which can handle errors but, i am getting error _api.default.get is not a function.
// My Axios Interceptor File
import axios from 'axios';
import {Config} from './common';
import {AsyncStorage} from '#react-native-community/async-storage';
const TIMEOUT = 1 * 60 * 1000;
axios.defaults.timeout = TIMEOUT;
axios.defaults.baseURL = Config.apiUrl;
const axiosInterceptors = async () => {
const token = await AsyncStorage.getItem('token');
const onRequest = config => {
if (token) {
config.headers.common.Authorization = `Bearer ${token}`;
}
return config;
};
const onSuccess = response => {
return response.data;
};
const onError = error => {
return Promise.reject(error);
};
axios.interceptors.request.use(onRequest);
axios.interceptors.response.use(onSuccess, onError);
};
export default axiosInterceptors;
and in my reducer
import axiosInterceptors from "../api"
export const fetchData = () => {
return dispatch => {
axiosInterceptors.get(apiUrl).then(something).catch(something)
}
}
It's work for me
const axiosInterceptors = axios.create({
baseURL: "your base url",
timeout: 500,
headers: {
Accept: "application/json",
Authorization: "Bearer "
}
});
API.interceptors.request.use(
async function(config) {
axios.defaults.timeout = 500;
const token = await AsyncStorage.getItem('token');
config.headers.Authorization = "Bearer ".concat(token);
return config;
},
function(error) {
return Promise.reject(error);
}
);
export default axiosInterceptors;

How to use Async Storage Axios

Problem:
I have create react-native application.And there I am using AsyncStorage with axios in like this to handle my API calls.This is how that looks like.
import axios from "axios";
import { AsyncStorage } from "react-native";
// TODO: Replace this with actual JWT token from Keycloak
axios.defaults.headers.post["Content-Type"] = "application/json";
// Create axios instance for api calls
var instance = null;
export const setAuth = async () => {
const user = await AsyncStorage.getItem("jwt");
AsyncStorage.getItem("jwt").then(token => {
instance = axios.create({
baseURL: "",
timeout: 150000,
headers: {
Authorization: "Bearer " + token,
"Content-Type": "application/json"
}
});
instance.interceptors.response.use(
function(response) {
return response;
},
async function(error) {
if (error.response.status) {
return error;
}
}
);
});
};
export const Get = (route, data) => {
instance || setAuth();
return instance.get(
route,
data == null ? { data: {} } : { data: JSON.stringify(data) }
);
};
export const Post = (route, data) => {
instance || setAuth();
return instance.post(route, JSON.stringify(data));
};
export const Put = (route, data) => {
debugger;
instance || setAuth();
return instance.put(route, JSON.stringify(data));
};
export const AddAdmin = (route, data) => {};
Becuase of the asynchronus property of AsyncStorage it is not creating the axios instanceinstance = axios.create({.The problem is with after this line .So can someone help me with this.I do not have any idea to find out what is wrong with this. Thank you.
You can give a try to this.
export const setAuth = async () => {
const token = await AsyncStorage.getItem('jwt');
instance = axios.create({
baseURL: '',
timeout: 150000,
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json'
}
});
// remaining Code
};
export const Get = (route, data) => {
function getData(){
return instance.get(
route,
data == null ? { data: {} } : { data: JSON.stringify(data) }
)
}
if(instance) return getData()
return setAuth().then(getData)
}