0

I am working on react native app. I am storing accesstoken in store after login. In every api call i have to pass this token as a header, but token has some expiry. So i have written one Apihandler class to refresh token. But here problem is i don't know how to access redux store in custom class. In react components using connect i can do mapStateToProps and dispatchProps. Please guide me to access store in custom javascript class.

Code:
import { store }   from  '../Store'
    export default class ApiHandler {
        static instance = null;

        static createInstance() {
            var object = new ApiHandler();
            return object;
        }

        static getInstance() {
            if (!ApiHandler.instance) {
                ApiHandler.instance = ApiHandler.createInstance();
            }
            return ApiHandler.instance;
        }
       callApi(){
         var token = store.getState().token (not working)

       } 
    }
skyshine
  • 2,767
  • 7
  • 44
  • 84
  • 1
    Have a look on this: https://daveceddia.com/access-redux-store-outside-react/ or this: https://stackoverflow.com/questions/38460949/what-is-the-best-way-to-access-redux-store-outside-a-react-component – gazdagergo Aug 23 '19 at 07:20
  • I tried to import store and access it, it is showing undefined . – skyshine Aug 23 '19 at 07:38
  • importing store and accessing working fine, how to dispatch action – skyshine Aug 23 '19 at 08:04

2 Answers2

0

As per https://daveceddia.com/access-redux-store-outside-react/

import { store }   from  '../Store'

accessing store : 

store.getState().loginReducer.userName

Dispatching store:

 store.dispatch({
          type: 'LOGIN_DATA',
          payload: 'Ram'
        })
skyshine
  • 2,767
  • 7
  • 44
  • 84
0

Here is a plain redux store with a mininal reading and writing example:

const reducer = (state, action) => {
  switch (action.type) {
    case 'REFRESH_TOKEN': return ({ token: action.payload });
    default: return ({ token: null });
  }
}

const store = Redux.createStore(reducer);

store.dispatch({
  type: 'REFRESH_TOKEN',
  payload: 'bar'
})

console.log(store.getState().token);
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.1/redux.min.js"></script>

Use import redux from 'redux' in a normal environment. This is just an inline verion of course.

gazdagergo
  • 6,187
  • 1
  • 31
  • 45