Search code examples
reactjsreactjs-fluxflux

How to make initial authenticated request with token from local storage?


I'm using vanilla flux with some utils for communicating with my APIs.

On initial page load I'd like to read some token from local storage and then make a request to my API to get my data.

I've got a LocalStorageUtils.js library for interacting with window.localStorage. My container component handles all login/logout actions and reads the current user on page load.

App.js

componentWillMount() {
  LocalStorageUtils.get('user');
}

LocalStorageUtils reads the value and brings it into Flux via ServerAction similar to the flux chat example.

get(key) {
  var value = window.localStorage.getItem(key);
  if (value) { 
    ServerActionCreators.receiveFromLocalStorage(key, value); 
  }
}

That puts the user into my UserStore and into my views where I can show the username and some logout link, etc.

I also have ApiUtils.js for requesting data from the server. So the question is: Where do I tell my ApiUtils that I have a logged-in user at initial page load?

I could call some method inside ApiUtils from my LocalStorageUtils but that does not feel right. Or do I have to make another round trip whenever I get a change event inside my container component?


Solution

  • I found a solution that works and feels right.

    As getting data from local storage is synchronous there is no need to pipe it through Flux via ServerActionCreators. Simply use LocalStorageUtils to get the current user and call the login method with that user. The login Action is the same you would use when a user initially logs in. login triggers getting new data from server. The new data is saved in my DataStore and the user is saved to my UserStore.

    Thanks for all hints at Twitter and at https://reactiflux.slack.com/.