{"id":19232653,"url":"https://github.com/makeomatic/redux-prefetch","last_synced_at":"2025-04-21T04:32:44.492Z","repository":{"id":57351246,"uuid":"48291576","full_name":"makeomatic/redux-prefetch","owner":"makeomatic","description":"add layer, which handles state prefetching for universal apps built with react-router and redux","archived":false,"fork":false,"pushed_at":"2017-08-11T16:28:16.000Z","size":14,"stargazers_count":15,"open_issues_count":0,"forks_count":1,"subscribers_count":6,"default_branch":"master","last_synced_at":"2025-04-14T03:39:47.042Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/makeomatic.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-12-19T17:49:04.000Z","updated_at":"2018-07-01T18:30:22.000Z","dependencies_parsed_at":"2022-09-18T23:41:35.797Z","dependency_job_id":null,"html_url":"https://github.com/makeomatic/redux-prefetch","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/makeomatic%2Fredux-prefetch","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/makeomatic%2Fredux-prefetch/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/makeomatic%2Fredux-prefetch/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/makeomatic%2Fredux-prefetch/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/makeomatic","download_url":"https://codeload.github.com/makeomatic/redux-prefetch/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249996158,"owners_count":21358076,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-09T16:07:05.986Z","updated_at":"2025-04-21T04:32:44.187Z","avatar_url":"https://github.com/makeomatic.png","language":"JavaScript","readme":"# Redux prefetch\n\nAllows universal server-side rendering to be performed without much hassle.\nExposes `@fetch` decorator and `storeEnchancer`, which keeps track of unresolved promises.\nAdd `.resolve` function to store\n\n## Install\n\n`npm i redux-prefetch -S`\n\n## Usage\n\nThe most important files are listed here, but look in the example for some extra stuff.\n\n```js\n// createStore.js\nimport { createStore, applyMiddleware, compose } from 'redux';\nimport promiseMiddleware from 'redux-promise-middleware';\nimport reducers from '../modules/reducers';\nimport { syncReduxAndRouter } from 'redux-simple-router';\nimport { canUseDOM as isBrowser } from 'fbjs/lib/ExecutionEnvironment';\nimport { reduxPrefetch } from 'redux-prefetch';\n\nexport default function returnStore(history, initialState) {\n  const middleware = [promiseMiddleware()];\n\n  let finalCreateStore;\n  if (isBrowser) {\n    finalCreateStore = applyMiddleware(...middleware);\n  } else {\n    finalCreateStore = compose(reduxPrefetch, applyMiddleware(...middleware));\n  }\n\n  const store = finalCreateStore(createStore)(reducers, initialState);\n  syncReduxAndRouter(history, store);\n\n  return store;\n}\n```\n\n```js\n// server.js\nimport React from 'react';\nimport merge from 'lodash/object/merge';\nimport { renderToString, renderToStaticMarkup } from 'react-dom/server';\nimport { match, RoutingContext } from 'react-router';\nimport routes from './routes';\nimport createStore from './store/create';\nimport metaState from './constants/config.js';\nimport HTML from './components/HTML';\nimport { Provider } from 'react-redux';\nimport serialize from 'serialize-javascript';\nimport DocumentMeta from 'react-document-meta';\n\nexport default function middleware(config = {}) {\n  const meta = merge({}, metaState, config);\n\n  // this is middleware for Restify, but can easily be changed for express or similar\n  return function serveRoute(req, res, next) {\n    match({ routes, location: req.url }, (err, redirectLocation, renderProps) =\u003e {\n      if (err) {\n        return next(err);\n      }\n\n      if (redirectLocation) {\n        res.setHeader('Location', redirectLocation.pathname + redirectLocation.search);\n        res.send(302);\n        return next(false);\n      }\n\n      if (!renderProps) {\n        return next('route');\n      }\n\n      // this is because we don't want to initialize another history store\n      // but apparently react-router passes (err, state) instead of (state), which\n      // is expected by redux-simple-router\n      const { history } = renderProps;\n      const { listen: _listen } = history;\n      history.listen = callback =\u003e {\n        return _listen.call(history, (_, nextState) =\u003e {\n          return callback(nextState.location);\n        });\n      };\n      const store = createStore(history, { meta });\n\n      // wait for the async state to resolve\n      store.resolve(renderProps.components, renderProps.params).then(() =\u003e {\n        const page = renderToString(\n          \u003cProvider store={store}\u003e\n            \u003cRoutingContext {...renderProps} /\u003e\n          \u003c/Provider\u003e\n        );\n        const state = store.getState();\n        const exposed = 'window.__APP_STATE__=' + serialize(state) + ';';\n        const html = renderToStaticMarkup(\u003cHTML meta={DocumentMeta.renderAsHTML()} markup={page} version=\"0.14.3\" state={exposed} /\u003e);\n\n        res.setHeader('content-type', 'text/html');\n        res.send(200, '\u003c!DOCTYPE html\u003e' + html);\n        return next(false);\n      });\n    });\n  };\n}\n```\n\n```js\nimport React, { Component, PropTypes } from 'react';\nimport { connect } from 'react-redux';\nimport DocumentMeta from 'react-document-meta';\nimport { dummy } from './modules/user' ;\nimport { fetch } from 'redux-prefetch';\n\nfunction prefetch({ dispatch, getState }, params) {\n  const timeout = parseInt(params.id || 30, 10);\n  if (getState().user.result !== timeout) {\n    return dispatch(dummy(timeout));\n  }\n}\n\n// this is the important part\n// it wraps the component with 2 handlers: componentDidMount() and static fetch()\n// static function is performed on the server for state resolution before rendering\n// the data\n// componentDidMount() is obviously only performed on the client. Because this state\n// will be already resolved on load, you need to make sure that necessary checks are performed\n// and async actions are not repeated again\n@fetch(\"root\", prefetch)\n@connect(state =\u003e ({ meta: state.meta, user: state.user }))\nexport default class App extends Component {\n  static propTypes = {\n    children: PropTypes.element,\n    meta: PropTypes.object.isRequired,\n    user: PropTypes.object.isRequired,\n  };\n\n  static contextTypes = {\n    store: PropTypes.object.isRequired,\n  };\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cDocumentMeta {...this.props.meta.app} /\u003e\n        \u003ch1\u003eHello world: {this.props.user.result}\u003c/h1\u003e\n        \u003cdiv\u003e{this.props.children \u0026\u0026 React.cloneElement(this.props.children, {\n          userId: this.props.user.result,\n        })}\u003c/div\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmakeomatic%2Fredux-prefetch","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmakeomatic%2Fredux-prefetch","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmakeomatic%2Fredux-prefetch/lists"}