Search code examples
node.jsreactjsreduxreact-reduxexpress-jwt

How do i dispatch a redux action from class and not component


import axios from "axios";

class ApiCaller {
    CallApi = (SERVICE_URL, data) => {
        return new Promise((resolve, reject) => {
            axios.post(SERVICE_URL, data).then(function (response) {
                var data = response.data
                if (data.status) {
                    data = data.data
                    resolve(data)
                } else {
                    if (data.isExpired != undefined && data.isExpired) {
                        console.log('here in expired')
                    }
                    reject(data.message)
                }
            }).catch(function (error) {
                console.log(error);
                reject(error)
            });
        })
    }
}


export default new ApiCaller();

// export default connect()(new ApiCaller());

here i am calling all the webservices throughout application and data.isExpired is a boolean where server tells me that provided jwt token is expired and i need to remove user information from redux and navigate to login again i have used this method almost more than 50 places and i cant afford it to change on all those places

how can i dispatch user logout from here ?

import { logoutUser } from "app/redux/actions/UserActions";

const mapStateToProps = state => ({
    logoutUser: PropTypes.func.isRequired
});

export default withRouter(connect(mapStateToProps, { logoutUser })(ApiCaller));

this might be the solution , to do that i need to extend component and it will break ApiCaller implementation on other places

i have tried functional components too but it isnt helping, i need to logout from my ApiCaller so i don't need to handle jwt expire exception on every single view i am new to React Redux

anyone please


Solution

  • I think this is a pretty good example of where you can use Redux Thunks.

    // this is an action that can be dispatched to call the api
    function callApi() {
      return (dispatch) => {
        apiCaller.CallApi()
          .then(() => {
            dispatch(callApiSuccess()); // success action defined elsewhere
          })
          .catch(() => {
            dispatch(callApiError()); // error action defined elsewhere
          });
      }
    }