redux-async-connect (original) (raw)

ReduxAsyncConnect for React Router

npm version

How do you usually request data and store it to redux state? You create actions that do async jobs to load data, create reducer to save this data to redux state, then connect data to your component or container.

Usually it's very similar routine tasks.

Also, usually we want data to be preloaded. Especially if you're building universal app, or you just want pages to be solid, don't jump when data was loaded.

This package consist of 2 parts: one part allows you to delay containers rendering until some async actions are happening. Another stores your data to redux state and connect your loaded data to your container.

Installation & Usage

Using npm:

$ npm install redux-async-connect

import { Router, browserHistory } from 'react-router';

import { ReduxAsyncConnect, asyncConnect, reducer as reduxAsyncConnect } from 'redux-async-connect'

import React from 'react'

import { render } from 'react-dom'

import { createStore, combineReducers } from 'redux';

@asyncConnect({

  lunch: (params, helpers) => Promise.resolve({id: 1, name: 'Borsch'})

})

class App extends React.Component {

  render() {

    const lunch = this.props.lunch

    return (

      

{lunch.name}

    )

  }

}

const store = createStore(combineReducers({reduxAsyncConnect}), window.__data);

render((

  

    <Router render={(props) => <ReduxAsyncConnect {...props}/>} history={browserHistory}>

      

    

  

), el)

Server

import { renderToString } from 'react-dom/server'

import { match, RoutingContext } from 'react-router'

import { ReduxAsyncConnect, loadOnServer, reducer as reduxAsyncConnect } from 'redux-async-connect'

import createHistory from 'history/lib/createMemoryHistory';

import {Provider} from 'react-redux';

import { createStore, combineReducers } from 'redux';

app.get('*', (req, res) => {

  const history = createHistory();

  const store = createStore(combineReducers({reduxAsyncConnect}));

  match({ routes, location: req.url }, (err, redirect, renderProps) => {

    loadOnServer(renderProps, store).then(() => {

      const appHTML = renderToString(

        

          <ReduxAsyncConnect {...renderProps} />

        

      )

      const html = createPage(appHTML, store)

      res.send(html)

    })

  })

})

function createPage(html, store) {

  return `

    

    

      

        ${html}

        

        <script dangerouslySetInnerHTML={{__html: window.__data=${serialize(store.getState())};}} charSet="UTF-8"/>

      

    

  `

}

API

Comparing with other libraries

There are some solutions of problem described above:

Redux Async Connect uses awesome Redux to keep all fetched data in state. This integration gives you agility:

Also it's integrated with React Router to prevent routing transition until data is loaded.

Contributors

Collaboration

You're welcome to PR, and we appreciate any questions or issues, please open an issue!