2.5.0 • Published 5 years ago

spud-framework v2.5.0

Weekly downloads
57
License
MIT
Repository
github
Last release
5 years ago

Overview

Spud framework is a lightweight, strongly-typed, and declarative way to minimize boilerplate while using thunks with redux for asynchronous actions, implemented as a hook.

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.

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

const thunks = useThunks(actions);
{
  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

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.

const loading = isLoading(actions);

License

MIT

2.5.0

5 years ago

2.0.99

5 years ago

2.0.7

5 years ago

2.0.6

5 years ago

2.0.5

5 years ago

2.0.4

5 years ago

2.0.3

5 years ago

2.0.2

5 years ago

2.0.1

5 years ago

2.0.0

5 years ago

1.2.8

5 years ago

1.2.7

5 years ago

1.2.6

5 years ago

1.2.5

5 years ago

1.2.4

5 years ago

1.2.3

5 years ago

1.2.2

5 years ago

1.2.0

5 years ago

1.2.1

5 years ago

1.1.2

5 years ago

1.1.1

5 years ago

1.1.0

5 years ago

1.0.0

5 years ago