Kevin Etore
Kevin Etore

Reputation: 1124

Asyncstorage in Redux action

I'm trying to use my access token (stored in Asyncstorage) in a Redux action. This is my code:

export function fetchData() {
  const endpoint = 'someEndpoint.com';
  let accessToken = '';
  myAccessToken().then((token) => {
    accessToken = token;
  });

  return (dispatch) => {
    dispatch(getData());
    axios.get(endpoint, { headers: { 'access-token': accessToken } })
    .then(response => {
      dispatch(getDataSuccess(response.data));
    })
    .catch(error => {
      dispatch(getDataFailure(error));
    });
  };
}
const myAccessToken = async () => {
  try {
    const retrievedItem = await AsyncStorage.getItem('accessToken');
    return retrievedItem;
  } catch (error) {
    return null;
  }
};

But fetching of the key is obviously async, I'm not sure on how to use the accessToken in the API call. I'm not allowed to do something like this:

export function fetchData() {
  const endpoint = 'someEndpoint.com';
  myAccessToken().then((token) => {
    return (dispatch) => {
      dispatch(getData());
      axios.get(endpoint, { headers: { 'access-token': token } })
      .then(response => {
        dispatch(getDataSuccess(response.data));
      })
      .catch(error => {
        dispatch(getDataFailure(error));
      });
    };
  });
}

My Store:

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import app from './reducers';

export default function configureStore() {
  return createStore(app, applyMiddleware(thunk));
}

Update

In the end I did it a little bit different, In my componentDidMount:

componentDidMount() {
    AsyncStorage.getItem('accessToken').then((accessToken) => {
      this.setState({ accessToken });
      this.props.fetchData(accessToken);
    });
  }

Thanks, Kevin.

Upvotes: 0

Views: 970

Answers (1)

alexgomez0120
alexgomez0120

Reputation: 11

I think you should use redux-thunk library for asynchronous updates of the redux state. It's easy to configure in the store.js file:

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';

// Note: this API requires redux@>=3.1.0
const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
);

Then, I would implement it like this:

export function fetchData() {
  return async function(dispatch) {
     const endpoint = 'someEndpoint.com';
     const accessToken = await myAccessToken();
     try {
        const response = await axios.get(endpoint, { headers: { 'access-token': accessToken } });
        return dispatch(getDataSuccess(response.data));
     } catch (error) {
        return dispatch(getDataFailure(error));
     }
  }
}

Upvotes: 1

Related Questions