0.1.1 • Published 6 years ago

redux-async-loading v0.1.1

Weekly downloads
4
License
MIT
Repository
github
Last release
6 years ago

Redux Async Loading

Tired of dispatching loading state for async actions? Try redux-async-loading!

Installation

 yarn add redux-async-loading
 // or
 npm install redux-async-loading --save

Usage

Notice that Redux Async Loading is based on Redux Thunk.

Step 1: Writing models

actions/count.js

export default (dispatch) => ({
  async increment () {
    await new Promise(resolve => setTimeout(resolve, 1000))
    // add your dispatch here
  },
})

actions/index.js

export { default as count } from './count'

Step 2: Init

store.js

import { createStore, applyMiddleware, combineReducers } from 'redux'
import thunk from 'redux-thunk'
import createReduxAsyncLoadingMiddleware, {
  createReducer,
  getInitialState,
} from 'redux-async-loading'
import * as actions from '@/actions'
import reducer from '@/reducers'

// create Loading reducer
const Loading = createReducer(
  getInitialState(actions)
)

const combinedReducers = combineReducers({
  Loading,
  // other reducers
  ...reducer,
})

const middleware = [
  createReduxAsyncLoadingMiddleware(actions),
  thunk,
]

const store = createStore(
  reducer,
  applyMiddleware(...middleware),
)

Step 3: View

import React from 'react'
import { connect } from 'react-redux'

@connect(
  ({ Loading }) => ({
    loading: Loading.count.increment,
  })
)

class Count extends React.PureComponent {
  render () {
    const { dispatch, loading } = this.props

    return (
      <div>
        <button onClick={dispatch({ type: 'count/increment' })}> async action </button>
        {loading && <p> loading... </p>}
      </div>
    )
  }
}

Contribution

PR & issue welcome.

License

MIT

0.1.1

6 years ago

0.1.0

6 years ago

0.0.3

6 years ago

0.0.2

6 years ago

0.0.1

6 years ago