All Projects → woltapp → redux-autoloader

woltapp / redux-autoloader

Licence: MIT license
A higher order component for declarative data loading in React and Redux.

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to redux-autoloader

react-example-paginated-list-infinite-scroll
Follow a React tutorial series with three parts to build a powerful component in React.
Stars: ✭ 43 (-23.21%)
Mutual labels:  react-component, higher-order-component
React Bps
🔱 Create breakpoints to your component props
Stars: ✭ 64 (+14.29%)
Mutual labels:  react-component, higher-order-component
Refluent
A chainable & composable alternative React component API.
Stars: ✭ 75 (+33.93%)
Mutual labels:  react-component, higher-order-component
Virtual List
🧾 React Virtual List Component which worked with animation
Stars: ✭ 232 (+314.29%)
Mutual labels:  react-component
React Native demo
react-native实现网易新闻和美团,实现大部分页面。使用最新的react-navigation等组件,同时支持安卓和iOS设备。
Stars: ✭ 237 (+323.21%)
Mutual labels:  react-component
react-antd-formutil
Happy to use react-formutil in the project based on ant-design ^_^
Stars: ✭ 16 (-71.43%)
Mutual labels:  react-component
react-win32dialog
💠 Modeless, resizeable and moveable dialog boxes with a classic Windows look-and-feel. Comes with a lightweight window manager that supports window stacking.
Stars: ✭ 30 (-46.43%)
Mutual labels:  react-component
React Native Htmlview
A React Native component which renders HTML content as native views
Stars: ✭ 2,546 (+4446.43%)
Mutual labels:  react-component
react-input-trigger
React component for handling character triggers inside textareas and input fields. 🐼
Stars: ✭ 88 (+57.14%)
Mutual labels:  react-component
React Powerplug
🔌 Renderless Containers
Stars: ✭ 2,704 (+4728.57%)
Mutual labels:  react-component
React Email Editor
Drag-n-Drop Email Editor Component for React.js
Stars: ✭ 3,131 (+5491.07%)
Mutual labels:  react-component
React Sweet Progress
A way to quickly add a progress bar to react app 🌈
Stars: ✭ 239 (+326.79%)
Mutual labels:  react-component
rn-markdown
basic markdown renderer for react-native using the great https://github.com/chjj/marked parser
Stars: ✭ 21 (-62.5%)
Mutual labels:  react-component
React Sight
Visualization tool for React, with support for Fiber, Router (v4), and Redux
Stars: ✭ 2,716 (+4750%)
Mutual labels:  react-component
react-power-select
A highly composable & reusable select/autocomplete components
Stars: ✭ 63 (+12.5%)
Mutual labels:  react-component
React Kawaii
Cute SVG React Components
Stars: ✭ 2,709 (+4737.5%)
Mutual labels:  react-component
react-listener-provider
Create a ReactListenerProvider and use HOC (Higher Order Components) to listen for Events in one place.
Stars: ✭ 19 (-66.07%)
Mutual labels:  higher-order-component
Sweetalert React
Declarative SweetAlert in React
Stars: ✭ 244 (+335.71%)
Mutual labels:  react-component
Boundless
✨ accessible, battle-tested React components with infinite composability
Stars: ✭ 242 (+332.14%)
Mutual labels:  react-component
React Emoji Render
Normalize and render emoji's the way your users expect.
Stars: ✭ 250 (+346.43%)
Mutual labels:  react-component

redux-autoloader

npm version Download Count

A higher order component for declarative data loading in React and Redux.

Install

  1. Install via NPM
npm install --save redux-autoloader
  1. Register reducer in your root reducer

The reducer must be mounted at reduxAutoloader.

import { reducer as reduxAutoloaderReducer } from 'redux-autoloader';

const rootReducer = combineReducers({
  ...
  reduxAutoloader: reduxAutoloaderReducer,
  ...
});
  1. Register saga
import { saga as reduxAutoloaderSaga } from 'redux-autoloader';

...
sagaMiddleware.run(reduxAutoloaderSaga);
...

Peer dependencies

  • react
  • redux
  • react-redux
  • redux-saga

Try demo locally

git clone https://github.com/woltapp/redux-autoloader.git
cd redux-autoloader
npm install
npm start

What problem does the library solve?

Attaching an API end-point to a view is such a common task that we decided to create a module to remove unnecessary boilerplate from most of the views and to greatly speed up the development. With redux-autoloader you can decorate any component and automatically load data from an API. The higher order component will provide you the props for handling the state; whether it returned data, is currently loading or returned an error. Moreover, the data can be automatically reloaded both periodically or manually. The library removes the tedious work of writing the logic of handling common request/success/failure state, registering refreshing and cache invalidation.

Examples

Super simple data loader

import { reduxAutoloader } from 'redux-autoloader';
...

const ExampleComponent = ({
  data,       // provided by reduxAutoloader
  error,      // provided by reduxAutoloader
  isLoading,  // provided by reduxAutoloader
}) = (
  <div>
    {isLoading && 'Loading data'}

    {error ? JSON.stringify(error) : (
      <div>
        Your data: {JSON.stringify(data)}
      </div>
    )}
  </div>
);

const ConnectedComponent = reduxAutoloader({
  name: 'example-loader-1',   // A unique name for the loader
  apiCall: yourDataFech,      // A function that returns a promise
})(ExampleComponent);

Set cache expiration and prevent excessive page loads

const ConnectedComponent = reduxAutoloader({
  name: 'example-loader-2',
  apiCall: yourDataFech,
  reloadOnMount: false, // Prevent triggering reload on mount, default: true
  cacheExpiresIn: 60000, // Set cache expiration time: data will be
  // loaded on mount after 1 minute even if reloadOnMount=false
})(ExampleComponent);

Set auto-refresh

const ConnectedComponent = reduxAutoloader({
  name: 'example-loader-3',
  apiCall: yourDataFech,
  autoRefreshInterval: 5000, // Set loader to automatically refetch data every 5 seconds.
  // Can be stopped by calling props.stopRefresh().
})(ExampleComponent);

Reload (refresh) when prop changes

const ConnectedComponent = reduxAutoloader({
  name: 'example-loader-3',
  apiCall: yourDataFech,
  reload: (props, nextProps) => props.myProp !== nextProps.myProp, // Watch when `myProp`
  // changes and reload
})(ExampleComponent);

API Documentation

reduxAutoloader(options, mapStateToProps) takes options (Object) as first (required) argument and mapStateToProps (Function) as second (optional) argument.

Options

  • name (String|Function -> String): A unique name for the loader (string) or a function that returns a name. If you make multiple loaders with the same name, they will share the same data (state). - always required - example: name: 'all-users' - example: name: props => `user-loader-${props.userId}`

  • apiCall (Function -> Promise): A function that returns a promise, which is usually an API call. If you want to provide arguments for the function, simply wrap it in a function that gets props as an argument. If left undefined, reduxAutoloader can be used simply as a connector to the data state. - example: apiCall: props => fetchUser(props.userId) - default: undefined

  • startOnMount (Bool): Control the behavior of the loader on mount. Set to false if you do not want load on mount and you don't want to start autorefreshing automatically (if autoRefreshInterval is set). - default: true (enable refresh on mount and start auto refreshing)

  • autoRefreshInterval (Number|Function -> Number): Provide an integer in milliseconds to define the interval of automatic refreshing. You can define also a function to return interval dynamically based on props. If set to 0 or undefined, automatic refresh won't be started. - default: 0 (no auto refreshing) - example: autoRefreshInterval: props => props.interval

  • loadOnInitialize (Bool): Control whether to load the data immediately after initialization (component mounted). - default: true

  • cacheExpiresIn (Number): Set the data expiration time, leavy empty for no expiration. If set, cache expiration will be checked on componentWillMount. Use with reloadOnMount: false to e.g. prevent excessive page loads. - default: 0 (no expiration)

  • reloadOnMount (Bool): Control whether reload is done always on component re-mount.

    • default: true
  • resetOnUnmount (Bool): Control whether to completely reset data-loader state on unmount.

    • default: true
  • reload (Function -> Bool): This function is run when the decorated component receives new props. The function takes props (current props) as first argument and nextProps as second. When the function returns true, it performs a refresh on the data loader. Compared to reinitialize (below), this won't reset the loader state. - example: reload: (props, nextProps) => props.userId !== nextProps.userId - default: () => false - ! NOTE ! setting reload: () => true or any other function that returns always true will cause an infinite loop (do not do this!)

  • reinitialize (Function -> Bool): This function is run when the decorated component receives new props. The function takes props (current props) as first argument and nextProps as second. When the function returns true, it resets the data loader; effectively re-mounting the component with a clean loader state. - example: reinitialize: (props, nextProps) => props.userId !== nextProps.userId - default: () => false - ! NOTE ! setting reinitialize: () => true or any other function that returns always true will cause an infinite loop (do not do this!)

  • pureConnect (Bool): This library uses connect() from react-redux under hood. Set pureConnect: false if you wish to prevent connect() from controlling component updates based on props.

    • default: true
  • renderUninitialized (Bool): Render wrapped component when the loader state has not yet been initialized.

    • default: false

mapStateToProps

mapStateToProps is an optional function to provide if you want to select only some props of the loader state or wish to rename them.

Example:

const ConnectedComponent = reduxAutoloader(options, state => ({
  isLoadingUsers: state.isLoading,
  users: state.data,
}));

Props

Props provided to the wrapped component.

  • isLoading (Bool): true if apiCall is triggered and not yet resolved.
  • isRefreshing (Bool): true if loader is auto-refreshing.
  • data (any): Resolved data received from the apiCall Promise.
  • dataReceivedAt (Number): Datetime as UNIX epoch when data was received.
  • error (any): Rejected data received from the apiCall Promise.
  • errorReceivedAt (Number): Datetime as UNIX epoch when error was received.
  • refresh (Function): Call to refresh (reload) data immediately.
  • startAutoRefresh (Function): Call to start auto-refreshing. Takes refreshInterval as first optional argument. Takes options object as second argument. Set options={ loadImmediately: false } to start refreshing but skip first load.
  • stopAutoRefresh (Function): Call to stop auto-refreshing.

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].