UNPKG

spud-framework

Version:

Spud framework is a lightweight, strongly-typed, and declarative way to minimize boilerplate while using [thunks](https://github.com/reduxjs/redux-thunk) with [redux](https://react-redux.js.org/) for asynchronous actions, implemented as a [hook](https://r

230 lines (167 loc) 5.6 kB
# Overview Spud framework is a lightweight, strongly-typed, and declarative way to minimize boilerplate while using [thunks](https://github.com/reduxjs/redux-thunk) with [redux](https://react-redux.js.org/) for asynchronous actions, implemented as a [hook](https://reactjs.org/docs/hooks-intro.html). The framework generates a thin, business-logic free reducer, action creators, and a hook for use in components. # Motivation React apps usually require data fetching from APIs, and Redux is a passe but convenient way to store this data as global application state, as the same data is frequently required across multiple application domains. Data fetching is obviously asynchronous, and thunks are a common solution to this requirement. This is often abstracted to a service layer in combination with thunks. A thunk's status can be represented as a simple state machine: ``` +------------<-----------reset-----------<------------+ | ^ | +-----onError-----> Error v ^ Idle ---call---> Waiting -------+ ^ v | +----onSuccess----> Success | v +------------<-----------reset-----------<------------+ ``` UI state often depends on the status of a thunk - we generally render states corresponding to the state of the data. Frequently, we On subsequent calls to the same API a thunks status must be manually reset to idle. # Usage In this example we're keen bird watchers, because let's be real, it's only marginally less boring than a to-do list. ```typescript service.ts ---------- export type Bird = { species: string description: string } export const scanBirds = (): Promise<Bird[]> => { // where you make a call to your choice bird API return new Promise((res, rej) => { setTimeout(() => { res([ { species: 'Bin Chicken', description: 'A truly disgusting creature' }, { species: 'Bondi Seagull', description: 'An aggressive chip fiend' }, { species: 'Rainbow Lorikeet', description: 'A friendly colorful delight' } ]) }, 1500); }) } export const scrutinizeBird = (bird: Bird): Promise<string> => { return new Promise((res, rej) => { setTimeout(() => { Math.round(Math.random()) ? res(`wow. what a great ${bird.name}`) : rej(`the ${bird.name} is too far away. birdwatching is fun.`); }, 1500); }) } types.ts -------- export const { scan: 'SCAN', examine: 'EXAMIME' } as const; actions.ts ---------- import { scanBirds } from './service'; import { types } from './types'; export const actionSchema = { scanBirds: { type: types.scan, sideEffect: scanBirds // this can be any async task, this example mocks fetching data }, scrutinizeBird: { type: types.scrutinize, sideEffect: scrutinizeBird } } component.ts ------------ import { useEffect, useSelector } from 'react' import { useThunks } from 'spud-framework' import { actionSchema } from './actions' import { Bird } from './service' type Props = { birds: Bird[] } const Ornithologist: React.FC = ({ birds }) => { const { scanBirds, watchBird } = useThunks(actionSchema) const { birds } = useSelector((state) => { birds: }) useEffect(() => { scanBirds.start() }) useEffect(() => { const bird = birds[0]; if (!bird) return; watchBird.cycle(bird); }, [birds]) return ( <> {birds.map(({ description, species }) => ( <> <h1> {species} </h1> <div> {description} </div> </> ))} </> ) } ``` # API #### `useThunks(actions: ActionSchema): ThunkHookActions` ```ts const thunks = useThunks(actions); ``` ```ts { actionName: { state: AsyncActionState; call: (...args: any): void; onSuccess: (cb: (data: D) => void) => void; onError: (cb: (error: E) => void) => void; reset: () => void; status: AsyncActionStatusConsts; } } ``` #### `thunk.start(...args: any): void` Kick off a thunk with `args` passed through to the async `sideEffect` function of your action. The thunk will remain in the `success` or `error` state after completion. Useful if your UI needs to conditionally render based on the outcome of the thunk. #### `thunk.cycle(...args: any): void` Same as `start`, but will also invoke `reset` on completion. Useful if your UI doesn't care about the outcome of a thunk. #### `thunk.status: AsyncActionStatusConsts` The thunk status, an enum of ```ts AsyncActionStatusConsts { Idle = 'idle', Waiting = 'waiting', Success = 'success', Error = 'error', } ``` #### `thunk.onSuccess(callback: (data: D) => void)` Called on transition from `waiting` to `success` with the resolved type of the `sideEffect` as `data: D` . #### `thunk.onError(callback: (error: E) => void)` Called on transition from `waiting` to `error` with the rejected type of the `sideEffect` as `error: E`. #### `thunk.reset(): void` Resets a thunks status from `success | error` back to `idle`. Note: this does not purge the data associated with the thunk from the store; it merely resets the status. ## Utility functions #### `isLoading(actions: ThunkHookActions): boolean` Useful if your loading state is dependant on multiple thunks completing. ```ts const loading = isLoading(actions); ``` # License MIT