@resuspend/redux
TypeScript icon, indicating that this package has built-in type declarations

1.0.0-rc11 • Public • Published

Resuspend Logo

@resuspend/redux

this integration of the core resuspend library w/ the Redux state management library provides a <ConnectedSuspension/> component which uses selectors, actions, and store state as the basis for implementing your suspension logic

npm node npm npm

getting started

To install the latest stable version:

npm i -s resuspend @resuspend/redux

basic example

here's a simple example of Redux based suspension logic.

starting with a base component:

import React from "react";

export const UserProfile = (props) => (
  <div>
    <h1>{props.user.name}</h1>
    <pre>@{props.user.id}</pre>
    <p>{props.user.status}</p>
    <button onClick={props.onRefresh}>Refresh</button>
  </div>
);

set up a typical connection between the base component and the store state:

import React, { useCallback } from "react";

// action creators
const setUser = (payload) => ({ type: 'SET_USER', payload });
const refreshUser = (payload) => ({ type: 'REFRESH_USER', payload });

// selectors
const getUserWithId = (userId) => (state) => state.userById[userId];

export const ConnectedUserProfile = (props) => {
  const getUser = useCallback(getUserWithId(props.userId), [props.userId]);

  const user = useSelector(getUser);
  const dispatch = useDispatch();

  const onRefresh = useCallback(() => {
    dispatch(refreshUser({ userId: props.userId }));
  }, [dispatch, props.userId]);

  return <UserProfile user={user} onRefresh={onRefresh} />;
};

then finally, you can define the suspension logic w/ selectors and assign it to the props of a <ConnectedSuspension> component:

import React, { useCallback } from "react";
import { ConnectedSuspension } from '@resuspend/redux';

import * as mocks from "../mocks"; // mock users for simulating fetch below

// activation status via a store selector
const noUserWithId = (userId) => (state) => !getUserWithId(userId)(state);

// activation effect via an action selector
const fetchUserWithId = (userId) => (state) => /* thunk you! */ (dispatch) => {
  // simulate fetch
  setTimeout(() => {
    const user = mocks.users[userId];
    dispatch(setUser({ user }));
  }, 2000);
};

export const SuspendableConnectedUserProfile = (props) => {
  const noUser = useCallback(noUserWithId(props.userId), [props.userId]);
  const fetchUser = useCallback(fetchUserWithId(props.userId), [props.userId]);

  return (
    <ConnectedSuspension activeSelector={noUser} onActiveSelector={fetchUser}>
      <ConnectedUserProfile {...props} />
    </ConnectedSuspension>
  );
};

try it out now in a live editor via CodeSandbox

Package Sidebar

Install

npm i @resuspend/redux

Weekly Downloads

1

Version

1.0.0-rc11

License

MIT

Unpacked Size

23.2 kB

Total Files

14

Last publish

Collaborators

  • json2d