pressly/react-transact

Name: react-transact

Owner: Pressly Inc.

Description: Simple, effortless way to fetch data and make them available to React components.

Created: 2016-04-29 15:41:15.0

Updated: 2017-07-18 11:52:43.0

Pushed: 2016-08-31 15:09:05.0

Homepage:

Size: 583

Language: JavaScript

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

React Transact

Simple, effortless way to fetch async data or perform computations, then make the results available to React components.

Works with Redux and React-Router out of the box. Also supports server-side rendering!

This project draws a lot of inspiration from the data.task library of Folktale. I highly recommend you check Folktale out!

For a quick in-browser example, check out the Counter app.

Note: This is an early release of this library, so expect API to change in the future. I will try to keep public API as stable as possible, and strive to make additive changes as much as possible.

Goal

The main goal of this project is to make data fetching as simple, effortless, and robust as possible. There should only be one obvious way to fetch and populate data in an application. Fetching data must be guaranteed to succeed or fail, as well maintain ordering (e.g. total ordering of fetch requests). Mechanisms for failure recovery should be dead simple – this is currently a work-in-progress, and only exposed as a low-level API (Task#orElse).

React Transact aims to make data fetching declarative and robust. This is achieved via the @transact decorator and the Task<A,B> type. All data fetching should go through transact.run function, which will ensure correct ordering, and predictable resolution. (transact is provided as a prop to @transacted components)

The Task<A,B> structure represents a disjunction for actions that depend on time. It can either contain a failure action of type A, or a successful action of type B. Projections on Task<A,B> is biased towards the right, successful value (of type B).

rt {Task} from 'react-transact'
Task.resolve({ type: 'RESOLVED', payload: 1 })
p(({ type, payload }) => ({ type, payload: payload + 1 })
This fork will succeed with `{ type: 'RESOLVED', payload: 2 }`
because the `map` will map over the successful payload value.
rk(
failedAction) => console.log('Something went wrong', failedAction),
successAction) => console.log('Yay', successAction)

Usage

The following examples show how React Transact can be used in applications.

Basic

The following is an async Hello World example.

rt React, {Component} from 'react'
rt {RunContext, transact, taskCreator} from 'react-transact'

reates a function that returns a Task when invoked.
t sendMessage = taskCreator(
RROR',      // action type for failure
ESSAGE',    // action type for success
ync x => x  // async function for payload resolution


rap the HelloWorld component with @transact decorator.
ote: You can also use it as a plain function `transact(...)(HelloWorld)`.
nsact(
tate, props, commit) => [
sendMessage('Hello World!')


s HelloWorld extends Component {
nder() {
// `transact` prop is passed down from `@transact`
// It makse the store available whether you use Redux or not.
const { message } = this.props.transact.store.getState()
return <h1>{message}</h1>



educer for our RunContext's local component state. (Redux not used here)
t stateReducer = (state = {}, action) => {
 (action.type === 'MESSAGE') {
return { message: action.payload }
else {
return state



tDOM.render(
unContext stateReducer={stateReducer}>
<HelloWorld/>
RunContext>,
cument.getElementById('app')

Please see the examples folder more use-cases, including server-side rendering.

Redux and React Router

This is the main use-case of React Transact.

Install the Redux middleware and render RouterRunContext:

rt React from 'react'
rt ReactDOM from 'react-dom'
rt {install, RouterRunContext, transact, taskCreator} from 'react-transact'
rt {Provider, connect} from 'react-redux'
rt {Router, Route} from 'react-router'
rt {createStore, applyMiddleware} from 'redux'

t reducer = (state = {}, action) => {
 (action.type === 'ECHO')
return { message: action.payload }
se
return state


t transactMiddleware = install()

ote: `install()` returns a middleware with a `done` prop that is a Promise
hat resolves when all tasks are resolved on matched routes.
his is needed if you are doing server-side rendering.
sactMiddleware.done.then(() => console.log('data loaded!'))

t store = createStore(reducer, undefined, applyMiddleware(transactMiddleware))

t echo = taskCreator('FAILED', 'ECHO', x => x)

nsact.route(

params: ['what'] // This will map to the path param as defined by the route.

what }) => echo(what) // This will only execute when `what` changes.

nect(state => state.message)
s EchoHandler extends React.Component {
nder() {
return <p>{ this.props.message }</p>



tDOM.render(
rovider store={store}>
<Router render={props => <RouterRunContext {...props}/>}>
  <Route path="/:what" component={EchoHandler}/>
</Router>
Provider>,
cument.getElementById('app')

Development

Fork and clone this repo.

Install dependencies:

install

Run tests:

test

Or, with faucet (recommended):

test | faucet

Run tests with watch support (working on improving this):

run test:watch

Build to ES5 (output is umd/ReactTransact.js):

run build
Contributing

Contributions are welcome! If you find any bugs, please create an issue with as much detail as possible to help debug.

If you have any ideas for features, please open up an issue or pull-request.

All pull-requests will be carefully reviewed, and merged once deemed satisfactory.

Documentation, fixing typos, etc. are definitely welcome as well!

Alternative Projects

Here are other projects that solve the async data problem.


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.