Inus Saha
Inus Saha

Reputation: 1918

How do I access the redux store from a helper class or function

I have the access token stored on the Redux store and I want to send it with each API request where authentication is needed. I have a class for API functions. Which is kind of a library. I am not sure how I can access the token from the API class.

Can anyone help regarding this?

Upvotes: 2

Views: 2444

Answers (2)

Rmjs
Rmjs

Reputation: 86

If you need have access from your component and considering you have a reducer called user and in your initial state you have something like this:

const INITIAL_STATE = {
  logged: false  
}

1. import { connect } from 'react-redux'

  1. Create your mapStateToProps like:

    const mapStateToProps = (state) => { return { logged: state.user.logged } }

  2. As a good practice create a prop in your component:

    MyComponent.propTypes = { logged: PropTypes.bool }

Upvotes: 0

Shashank Srivastava
Shashank Srivastava

Reputation: 509

You have to import store in the file you need to access the store from your respective index file, i have done it like this

import { store } from '../index';

 store.subscribe(() => {
      store.getState();
      token = store.getState().Login.token; //access token here
 })

In the index.android.js/index.ios.js i have exported store

export const store = createStore(
  RootReducer,
  undefined,
  // the ordering of middleware is significant.
  applyMiddleware(thunk),
);

Upvotes: 6

Related Questions