I have a helper.js file which contains all the helper function including the HTTP request handler with axios. Here are my helper.js file codes:
const HTTPRequest = (path, body, method = 'POST', authorizedToken = null) => {
return new Promise((resolve, reject) => {
let headers = {
'Content-type': 'multipart/form-data',
};
// Set authorization token
if (authorizedToken) {
headers['Authorization'] = "JWT " + authorizedToken; // Here i want to get user token from the redux store not though passing the token
}
const fulHeaderBody = {
method,
headers,
timeout: 20,
url: path
};
axios(fulHeaderBody).then(response => {
if (response.success) {
resolve(response);
} else {
// Show toast about the error
Toast.show({
text: response.message ? response.message : 'Something went wrong.',
buttonText: 'Okay',
type: 'danger'
});
resolve(response);
}
}).catch(error => {
if (error.response) {
if(error.response.status === 401){
// I WANT TO DISPATCH AN ACTION HERE TO LOGOUT CLEAR ALL STORAGE DATA IN REDUX AND CHANGE THE STATE TO INITIAL
}else{
console.log('Error', error.message);
}
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
reject(error);
})
});
};
export default HTTPRequest;
Now then, the problem I am facing is that, how can I dispatch an action from this helper function or how can I get user token from the redux store.
I have tried creating an action name in action.js like this
export function helloWorld() {
console.log('Hello world has been dispatched');
return function(dispatch){
dispatch(helloWorldDispatch());
}
}
function helloWorldDispatch() {
return {
type: 'HELLO_WORLD'
}
}
and in the reducer :
switch (action.type) {
case 'HELLO_WORLD': {
console.log('Hello world Current state',state);
return state
}
default:
return state
}
And calling it from helper.js like this
inside HTTPRequest function
helloWorld();
I can see only the log Hello world has been dispatched, but I don not see any log from the dispatcher.
Can anyone please tell how can I handle this. ?