{"id":13437898,"url":"https://github.com/markdalgleish/redial","last_synced_at":"2025-05-15T14:05:29.920Z","repository":{"id":57333270,"uuid":"45404868","full_name":"markdalgleish/redial","owner":"markdalgleish","description":"Universal data fetching and route lifecycle management for React etc.","archived":false,"fork":false,"pushed_at":"2018-06-13T07:07:21.000Z","size":48,"stargazers_count":1100,"open_issues_count":14,"forks_count":42,"subscribers_count":15,"default_branch":"master","last_synced_at":"2025-04-15T03:54:45.568Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/markdalgleish.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-11-02T15:56:56.000Z","updated_at":"2025-02-26T09:35:35.000Z","dependencies_parsed_at":"2022-08-24T21:01:53.662Z","dependency_job_id":null,"html_url":"https://github.com/markdalgleish/redial","commit_stats":null,"previous_names":["markdalgleish/react-fetcher"],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/markdalgleish%2Fredial","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/markdalgleish%2Fredial/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/markdalgleish%2Fredial/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/markdalgleish%2Fredial/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/markdalgleish","download_url":"https://codeload.github.com/markdalgleish/redial/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254355334,"owners_count":22057354,"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-07-31T03:01:01.034Z","updated_at":"2025-05-15T14:05:24.908Z","avatar_url":"https://github.com/markdalgleish.png","language":"JavaScript","readme":"[![Build Status](https://img.shields.io/travis/markdalgleish/redial/master.svg?style=flat-square)](http://travis-ci.org/markdalgleish/redial) [![Coverage Status](https://img.shields.io/coveralls/markdalgleish/redial/master.svg?style=flat-square)](https://coveralls.io/r/markdalgleish/redial) [![npm](https://img.shields.io/npm/v/redial.svg?style=flat-square)](https://www.npmjs.com/package/redial)\n\n# redial\n\nUniversal data fetching and route lifecycle management for React etc.\n\n```bash\n$ npm install --save redial\n```\n\n## Why?\n\nWhen using something like [React Router](https://github.com/rackt/react-router), you'll want to ensure that all data for a set of routes is prefetched on the server before attempting to render.\n\nHowever, as your application grows, you're likely to discover the need for more advanced route lifecycle management.\n\nFor example, you might want to separate mandatory data dependencies from those that are allowed to fail. You might want to defer certain data fetching operations to the client, particularly in the interest of server-side performance. You might also want to dispatch page load events once all data fetching has completed on the client.\n\nIn order to accommodate these scenarios, the ability to define and trigger your own custom route-level lifecycle hooks becomes incredibly important.\n\n## Providing lifecycle hooks\n\nThe `@provideHooks` decorator allows you to define hooks for your custom lifecycle events, returning promises if any asynchronous operations need to be performed. When using something like React Router, you'll want to decorate your route handlers rather than lower level components.\n\nFor example:\n\n```js\nimport { provideHooks } from 'redial';\n\nimport React, { Component } from 'react';\nimport { getSomething, getSomethingElse, trackDone } from 'actions/things';\n\n@provideHooks({\n  fetch: ({ dispatch, params: { id } }) =\u003e dispatch(getSomething(id)),\n  defer: ({ dispatch, params: { id } }) =\u003e dispatch(getSomethingElse(id)),\n  done: ({ dispatch }) =\u003e dispatch(trackDone())\n})\nclass MyRouteHandler extends Component {\n  render() {\n    return \u003cdiv\u003e...\u003c/div\u003e;\n  }\n}\n```\n\nIf you'd prefer to avoid using decorators, you can use `provideHooks` as a plain old function:\n\n```js\nconst hooks = {\n  fetch: ({ dispatch, params: { id } }) =\u003e dispatch(getSomething(id)),\n  defer: ({ dispatch, params: { id } }) =\u003e dispatch(getSomethingElse(id)),\n  done: ({ dispatch }) =\u003e dispatch(trackDone())\n};\n\nclass MyRouteHandler extends Component {\n  render() {\n    return \u003cdiv\u003e...\u003c/div\u003e;\n  }\n}\n\nexport default provideHooks(hooks)(MyRouteHandler);\n```\n\n### Triggering lifecycle events\n\nOnce you've decorated your components, you can then use the `trigger` function to initiate an event for an arbitrary array of components, or even a single component if required. Since hooks tend to be asynchronous, this operation always returns a promise.\n\nFor example, when fetching data before rendering on the server:\n\n```js\nimport { trigger } from 'redial';\n\nconst locals = {\n  some: 'data',\n  more: 'stuff'\n};\n\ntrigger('fetch', components, locals).then(render);\n```\n\n### Dynamic locals\n\nIf you need to calculate different locals for each lifecycle hook, you can provide a function instead of an object. This function is then executed once per lifecycle hook, with a static reference to the component provided as an argument.\n\nFor example, this would allow you to calculate whether a component is being rendered for the first time and pass the result in via the locals object:\n\n```js\nconst getLocals = component =\u003e ({\n  isFirstRender: prevComponents.indexOf(component) === -1\n});\n\ntrigger('fetch', components, getLocals).then(render);\n```\n\n## Example usage with React Router and Redux\n\nWhen [server rendering with React Router](https://github.com/rackt/react-router/blob/master/docs/guides/ServerRendering.md) (or using the same technique to render on the client), the `renderProps` object provided to the `match` callback has an array of routes, each of which has a component attached. You're also likely to want to pass some information from the router to your lifecycle hooks.\n\nIn order to dispatch actions from within your hooks, you'll want to pass in a reference to your store's `dispatch` function. This works especially well with [redux-thunk](https://github.com/gaearon/redux-thunk) to ensure your async actions return promises.\n\n### Example server usage\n\n```js\nimport { trigger } from 'redial';\n\nimport React from 'react';\nimport { renderToString } from 'react-dom/server';\nimport { RouterContext, createMemoryHistory, match } from 'react-router';\nimport { createStore, applyMiddleware } from 'redux';\nimport { Provider } from 'react-redux';\nimport thunk from 'redux-thunk';\n\n// Your app's reducer and routes:\nimport reducer from './reducer';\nimport routes from './routes';\n\n// Render the app server-side for a given path:\nexport default path =\u003e new Promise((resolve, reject) =\u003e {\n  // Set up Redux (note: this API requires redux@\u003e=3.1.0):\n  const store = createStore(reducer, applyMiddleware(thunk));\n  const { dispatch, getState } = store;\n\n  // Set up history for router:\n  const history = createMemoryHistory(path);\n\n  // Match routes based on history object:\n  match({ routes, history }, (error, redirectLocation, renderProps) =\u003e {\n    // Get array of route handler components:\n    const { components } = renderProps;\n\n    // Define locals to be provided to all lifecycle hooks:\n    const locals = {\n      path: renderProps.location.pathname,\n      query: renderProps.location.query,\n      params: renderProps.params,\n\n      // Allow lifecycle hooks to dispatch Redux actions:\n      dispatch\n    };\n\n    // Wait for async data fetching to complete, then render:\n    trigger('fetch', components, locals)\n      .then(() =\u003e {\n        const state = getState();\n        const html = renderToString(\n          \u003cProvider store={store}\u003e\n            \u003cRouterContext {...renderProps} /\u003e\n          \u003c/Provider\u003e\n        );\n\n        resolve({ html, state });\n      })\n      .catch(reject);\n  });\n});\n```\n\n### Example client usage\n\n```js\nimport { trigger } from 'redial';\n\nimport React from 'react';\nimport { render } from 'react-dom';\nimport { Router, browserHistory, match } from 'react-router';\nimport { createStore, applyMiddleware } from 'redux';\nimport { Provider } from 'react-redux';\nimport thunk from 'redux-thunk';\n\n// Your app's reducer and routes:\nimport reducer from './reducer';\nimport routes from './routes';\n\n// Render the app client-side to a given container element:\nexport default container =\u003e {\n  // Your server rendered response needs to expose the state of the store, e.g.\n  // \u003cscript\u003e\n  //   window.INITIAL_STATE = \u003c%- require('serialize-javascript')(state)%\u003e\n  // \u003c/script\u003e\n  const initialState = window.INITIAL_STATE;\n\n  // Set up Redux (note: this API requires redux@\u003e=3.1.0):\n  const store = createStore(reducer, initialState, applyMiddleware(thunk));\n  const { dispatch } = store;\n\n  // Listen for route changes on the browser history instance:\n  browserHistory.listen(location =\u003e {\n    // Match routes based on location object:\n    match({ routes, location }, (error, redirectLocation, renderProps) =\u003e {\n      // Get array of route handler components:\n      const { components } = renderProps;\n\n      // Define locals to be provided to all lifecycle hooks:\n      const locals = {\n        path: renderProps.location.pathname,\n        query: renderProps.location.query,\n        params: renderProps.params,\n\n        // Allow lifecycle hooks to dispatch Redux actions:\n        dispatch\n      };\n\n      // Don't fetch data for initial route, server has already done the work:\n      if (window.INITIAL_STATE) {\n        // Delete initial data so that subsequent data fetches can occur:\n        delete window.INITIAL_STATE;\n      } else {\n        // Fetch mandatory data dependencies for 2nd route change onwards:\n        trigger('fetch', components, locals);\n      }\n\n      // Fetch deferred, client-only data dependencies:\n      trigger('defer', components, locals);\n    });\n  });\n\n  // Render app with Redux and router context to container element:\n  render((\n    \u003cProvider store={store}\u003e\n      \u003cRouter history={browserHistory} routes={routes} /\u003e\n    \u003c/Provider\u003e\n  ), container);\n};\n```\n\n## Boilerplates using redial\n\n- [React Production Starter](https://github.com/jaredpalmer/react-production-starter) by [@jaredpalmer](https://twitter.com/jaredpalmer)\n- [Redux universal boilerplate](https://github.com/ufocoder/redux-universal-boilerplate) by [@xufocoder](https://twitter.com/xufocoder)\n\n## Related projects\n\n- [React Resolver](https://github.com/ericclemmons/react-resolver) by [@ericclemmons](https://twitter.com/ericclemmons)\n- [React Transmit](https://github.com/RickWong/react-transmit) by [@rygu](https://twitter.com/rygu)\n- [AsyncProps for React Router](https://github.com/rackt/async-props) by [@ryanflorence](https://twitter.com/ryanflorence)\n- [GroundControl](https://github.com/raisemarketplace/ground-control) by [@nickdreckshage](https://twitter.com/nickdreckshage)\n- [React Async](https://github.com/andreypopp/react-async) by [@andreypopp](https://twitter.com/andreypopp)\n\n## License\n\n[MIT License](http://markdalgleish.mit-license.org/)\n","funding_links":[],"categories":["Uncategorized","Code Design","JavaScript"],"sub_categories":["Uncategorized","Props from server"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmarkdalgleish%2Fredial","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmarkdalgleish%2Fredial","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmarkdalgleish%2Fredial/lists"}