Skip to content

Instantly share code, notes, and snippets.

@pluma pluma/Loader.tsx
Last active Nov 28, 2017

What would you like to do?
Component for handling async data fetching with redux?
import { Error, ErrorType } from "./Error";
import { Loading } from "./Loading";
import React from "react";
type LoaderProps = {
id: string;
error?: Object;
data: any;
isLoading: boolean;
expires?: Number;
load: Function;
renderData: Function;
renderError: Function;
renderLoading: Function;
export type RenderProps = {
id: string;
error?: ErrorType;
data: any;
isLoading: boolean | null;
expires?: Number;
refresh: Function;
export class Loader extends React.Component<LoaderProps> {
componentDidMount() {
if (this.props.isLoading) return;
if (Number(this.props.expires) > return;
componentWillReceiveProps(newProps: LoaderProps) {
if ( === return;
if (newProps.isLoading) return;
if (Number(newProps.expires) > return;
render() {
const {
renderLoading = () => <Loading />,
renderError = ({ error, refresh }: RenderProps) => (
<Error error={error} refresh={refresh} />
} = this.props;
const renderChildren =
? renderData
: this.props.isLoading === false ? renderError : renderLoading;
return renderChildren({ refresh: () => load(, ...props });

This comment has been minimized.

Copy link
Owner Author

pluma commented Nov 27, 2017

The load prop updates the app state by setting isLoading to true and clearing the error while a side-effect fetches the data. If fetching succeeded, expires is updated, isLoading is set to false and data is set to the response. If fetching failed, error is set instead of data. Additionally expires may be set to a closer timestamp than normal to avoid caching temporary errors. The renderError method might include a retry button that calls the load prop. The renderData method might include a banner to indicate stale content is being refreshed or that refreshing the content failed (again with a retry button).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.