简体   繁体   中英

How can i dispatch an action from a helper function in react native

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. ?

I assume that you have already installed redux-thunk.

First you need to modify your HTTPRequest function in helper.js. add two more parameter to it dispatch as given below

const HTTPRequest = (path, body, method = 'POST',
                      authorizedToken = null,dispatch,actionCreator) => {

Then in success of your axios call you can add below line

 dispatch(actionCreator.success(response))

similarly for failure you can add as below

 dispatch(actionCreator.failure(error.message))

create an action in action.js file as

export const helperAction=(path, body, method = 'POST',
                      authorizedToken = null) =>{
var actionCreator = {}
actionCreator.success = helloWorld
actionCreator.failure = failureFunction //your failure action

return dispatch => {
  HTTPRequest(path, body, method = 'POST',
                      authorizedToken = null,dispatch, actionCreator)
 }
}

Create action creator and pass that as an argument along with dispatch to your HTTPREQUEST utility available in helper.js file. Now based upon the success and failure response it is initiating the action. using that action you can store the response in redux store and then you can use it in your component.

Updated answer below to solve exact problem. Otherwise I would recommend above solution. Try this

import store from './redux/store.js';
Const func=()=> {}

store.subscribe(func)

With the link shared by @Avin Kavish in the comment, here is my solution.

In the helper.js I have imported the store, and now the helper function looks like this

import {store} from "../redux/ConfigureStore"; //I have imported my store

const HTTPRequest = (path, body, method = 'POST', authorizedToken = false) => {
 let getInitialStates = store.dispatch(helloWorld()); //This to dispatch an action
   <ALL OTHER CODES AS ABOVE HERE>
}

This is because the store is an object which has few methods including dispatching an action as mention here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM