Skip to content
This repository has been archived by the owner on Feb 20, 2019. It is now read-only.

Where and how to update UI state for thunks? #60

Open
cidylle opened this issue Oct 20, 2016 · 3 comments
Open

Where and how to update UI state for thunks? #60

cidylle opened this issue Oct 20, 2016 · 3 comments

Comments

@cidylle
Copy link

cidylle commented Oct 20, 2016

Forgive me if the answer is trivial but I can't find an example in the documentation or elsewhere and I would like to give redux-ui a try and adapt my existing code to it. Where would you recommend updating the UI state for asynchronous actions wrapped around a redux-thunk such as retrieving a resource through an API?

For example I would just like to update a isLoading state specific to a component that depends on an asynchronous action (an API call, dispatching actionCreators such as IN_PROGRESS, SUCCESS which would modify the UI state). Any example or advice on how to structure and implement that with redux-ui ? Thank you.

@vanhtuan0409
Copy link

vanhtuan0409 commented Oct 28, 2016

I think this problem is not for redux-ui
When you fire an API call, usually 3 action could be fired

  • START_FETCHING (immediately after you call to API)
  • SUCCESS or ERROR (after receive response from server)

Loading state should be store in the same reducer which handle received data from server (not for UI state).

@br0wn
Copy link

br0wn commented Dec 1, 2016

If you're using redux-thunk, there's a nice thing of dispatch returning whatever the thunk returns, so you can have your async action return promise, and use that promise in your component to trigger UI update.

// action.js
export const asyncAction = () => (dispatch) => {
   return fetch(url, options).then( response => {
      // do something with response
      // ...
   });
}
// component.jsx

export class Component extends React.Component {
    doSomething(){
       this.updateUI({loading: true});

       this.dispatch(asyncAction()).then(
              () => this.updateUI({loading: false}
       ).catch(
              () => this.updateUI({loading: false, error: true}
       );
    }

   // ...
}

Please note that the code above is just a proof of concept and wasn't tested. Also, I don't know if this is bad practice or not, but it is useful when you don't want to add actions and reducer switches just to set some flag consumed by UI.. so be wary if using this approach :)

@cidylle
Copy link
Author

cidylle commented Dec 1, 2016

@br0wn It doesn't seem to me like a bad approach. Thanks for the tip I'll give it a try :)

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants