React Async Example (without Redux)

Followup to “You probably don’t need redux”.

My last article lamented the over-use/over-hype of using redux in your react apps. I’m not against redux, but I think react is better when you really understand it before pushing yourself to use redux.

Some feedback about my last article https://medium.com/@blairanderson/you-probably-dont-need-redux-1b404204a07f

It got some good feedback, and I wanted to followup and include a vanilla async example to backup my react-without-redux flow.


The Demo — Shows 3 states, not-loaded, loading, loaded.

https://www.blairanderson.co/react-no-redux/#async-example

The Code roughly 40 lines of javascript will cover enough logic for all 3 states. An error state could easily be added with another 10 lines of code. the Rest is visual styling around data existing or not.

testAsync(e) {    
const state = this.props.data;
e.preventDefault();
if (state.loaded || state.loading) {
// Prevent a duplicate request
// Could also cancel the previous request and start a new one.
return false;
}
  this.update({ loading: true });
  fetch(slowUrl)
.then(response => response.json())
.then(json => {
this.update({ loaded: true, loading: false, posts: json });
})
.catch(err => console.log('failed', err)); }

You can compare these with Redux example async request: http://redux.js.org/docs/advanced/ExampleRedditAPI.html (notice they place in the advanced folder 😜 )


Let me know what you think? if you have similar problems or examples would love to see them.

If you haven’t already, checkout my original article: