Git Product home page Git Product logo

retreon's Introduction

retreon

A type-safe, batteries-included redux toolkit.

Build status npm npm bundle size


Project Status

โ›” UNMAINTAINED

State management is still heavily evolving in React. While I believe Retreon is one of the best ways to use Redux, the community is modernizing towards modular hook-based libraries.

I would recommend exploring Recoil, Jotai, or any of the newer approaches.

Purpose

Redux is a phenomenally powerful tool, and it can be a true joy to work with. But it takes time to find good tooling and develop healthy patterns.

Retreon aims to provide good patterns and strong types out of the box, including tools for async actions and error handling. Retreon is FSA compliant.

Here's a taste:

// actions.ts
const fetchResource = createAction.async('fetch-resource', async (id: number) => {
  const response = await fetch(`/resources/${id}`)
  return response.json()
})
// reducer.ts
const reducer = createReducer(initialState, handleAction => [
  // Called as soon as the action starts
  handleAction.optimistic(fetchResource, (state, resourceId) => {
    state.loading = true
  }),

  // Optionally, handle errors if your action fails
  handleAction.error(fetchResource, (state, error) => {
    state.loading = false
  }),

  // Called when the action's promise resolves, passing the payload
  handleAction(fetchResource, (state, resource) => {
    state.loading = false
    state.resource = resource
  }),
])

If you prefer to learn by example, take a gander at the examples directory, or check out TodoMVC to see a functioning application.

Installation

Retreon can be installed through npm.

# NPM
npm install retreon

# Yarn
yarn add retreon

Retreon depends on middleware to implement async actions and error handling. Once it's installed, register it with your redux store:

// Wherever you create your redux store...
import { middleware } from 'retreon'

createStore(reducer, applyMiddleware(middleware))

Documentation

Documentation is hosted on the retreon website:


Retreon is inspired by redux-actions and immer.

retreon's People

Contributors

dependabot-preview[bot] avatar psychollama avatar renovate-bot avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

retreon's Issues

Investigate using tslib for a smaller runtime

tslib is similar to the babel runtime. I should do some bundle size comparisons to see if offloading bytes to tslib makes sense. The size cost should be balanced: this is an easy tradeoff for apps written in TypeScript (they've probably got the library already) but if it adds much size in vanilla, the tradeoff isn't worth it.

"never" case is bleeding into success handler payload type

It looks like there was a regression with action payload type inference. The never case is bleeding through. I suspect the failure action type branch is to blame.

Repro

const action = createAction('type', () => {
  return 'value'
})

createReducer(null, handleAction => [
  handleAction(action, (state, payload) => {
    //                         ^^^^^^^ never
  })
])

Use tsdx build system

I recently discovered the tsdx build system. It automates a lot of stuff I've been trying to do manually, and after (counts repositories) 45 projects, the thought of having someone else manage JS tooling sounds pretty dreamy. tsdx looks like it might be able to deliver, and a proof of concept against the todomvc demo app appears to work marvelously.

Remove type inference on error reducers

I'm removing the failure(...) return value and replacing it with a bulk catch for thrown errors, which means the error type is no longer inferable for handleAction.error(...). It will become unknown. I'll encourage custom errors and instance checks instead.

handleAction.error(action, (state, error) => {
  if (error instanceof SomeCustomError) {
    // do the thing
  }
})

Add support for synchronous iterators in middleware

Only async iterators are supported currently. That's causing some issues in #205 because I need synchronous execution, which is technically possible on the first tick of an async generator, but then the dispatch return value becomes a promise. That's certainly undesirable.

Now that I have a real use for them, I need proper support for synchronous iterators in the redux middleware.

function* dispatcher() {
  yield { type: 'action-1' }
  yield { type: 'action-2' }
  yield { type: 'action-3' }
  return 'return value of `dispatch(...)`'
}

Rip out special "failure" return value

Now that I'm moving towards throw statements instead of the failure(...) return value, I no longer need it. I should rip it out.

This will be a breaking change (obviously).

Make a logo

Retreon needs a logo for both the project and the organization.

Return dispatch results through yield expressions

Yielding an action should resume control with the return value of dispatch(...).

async function*() {
  const { type } = yield action()
}

and because this is all executed by the middleware, yielding another iterator will recursively consume all those yield statements as well, leading to some very interesting composition patterns.

Capture errors thrown in action creators

I need error reducers to intercept error events, not just those gracefully returned by failure(...). This means adding a catch statement on the effect, but as I outlined over here, I can't just swallow every error. That means conditionally re-throwing after dispatch is done.

The only way that's possible is through async generator functions.

async function* createAction(type, effect) {
  try {
    yield { type, payload: effect() }
  } catch (error) {
    yield { type, error: true, payload: error }
    if (isUnknown(error)) throw error
  }
}

Improve reducer type inference for advanced use cases

As an advanced use case, developers can dispatch actions through generator functions. Developers have to format their own action payloads, which makes reducer type inference difficult for error types and impossible for optimistic types.

const underlyingAction = createAction<string>('type')

async function* advanced() {
  // For reducer type inference to work, the optimistic payload must be part of the
  // action's return signature. Currently, there's no method to communicate it
  // without buying into `createAction.async(...)`.
  yield { type: String(underlyingAction), meta: {} }

  try {
    await effect()

    yield underlyingAction('works just fine')
  } catch (error) {
    // This is unwieldy, but still works with the reducers because `handleAction.error(...)`
    // infers the signature from `underlyingAction`. Alternatively, you could add a
    // boolean parameter to conditionally throw inside the action creator... yeah, I'm not
    // keen on it.
    yield { type: String(underlyingAction), ... }
  }
}

I'm tempted to create another action factory function, one that puts the onus of effect execution solely on the end developer, this way generator functions can leverage type inference and FSA compliant actions without much effort.

const underlyingAction = actionFactory<Payload, OptimisticPayload>('type')

async function* advanced() {
  yield underlyingAction.optimistic('optimistic payload')

  try {
    await effect()
    yield underlyingAction.success('success payload')
  } catch (error) {
    yield underlyingAction.failure(new Error('action failed'))
  }
}

It will require a new package export and type detection on reducers.

Add support for async action error handling

Now that I've settled on a consistent API, I can implement error handling for async action creators. Async actions should trigger handleAction.error(...) on any promise rejection.

const action = createAction.async('type', async function() {
  throw new Error('async rejection')
})

createReducer(state, handleAction => [
  handleAction.error(action, (state, error) => {
    console.log(error) // Error: async rejection
  }),
])

Create a functioning example app

I'd like a simple application where I can demo and test the features of retreon holistically, something along the lines of a TodoMVC clone. It would help greatly to have E2E smoke tests verifying that retreon actually works in harsh browser environments.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.