Giter Site home page Giter Site logo

react-router-fetch's Introduction

react-router-fetch

module to loop through matched react router handler to call fetch methods for specifying data needs at the handler level

Dependency Status Build Status Coverage Status

Why?

I wanted a nice and contained module to be able to initiate requests for route handlers in an app, so that the data would be loaded before the route handler was rendered. This module doesn't accomplish that on it's own, but can be used as a part of a solution to that problem.

Usage

react router fetch wraps react-router-config matchRoutes. It then will go through the routes in a similar fashion as the README suggests.

const App = (props) => (
  <div />
)

class Home extends Component {
  static fetch () {
    return new Promise((resolve, reject) => {
      setTimeout(resolve, 1000, { test: '1234' })
    })
  }
  render () {
    return (
      <div>Home</div>
    )
  }
}

const routes = [
  {
    component: App,
    routes: [
      {
        path: '/',
        exact: true,
        component: Home
      }
    ]
  }
]

reactRouterFetch(routes, { pathname: '/' })
  .then((results) => {
    //the results of the fetching are also here if you need them.
  })

in a component you would want to pass the this.props.location from react-router in order to have full access to that in the static fetch method on the component.

Specifying route data needs

This allows you to specify at the route handler level what data that route needs via a static fetch method. The fetching itself should be wired up to redux via thunks, or whatever way you want to handle that. the only requirement is that the static method returns a promise.

import React, { Component } from 'react'

class Page extends Component {

  static fetch(match, location, options) {
    //return a promise to be resolved later, superagent as an example
    return request('GET', '/search')
  }

  render() {
    //your stuff
  }
}

This module is intended to be a building block for other modules or as a low level part of your application.

Using in a top level component

Assuming you have a top level component, you can export it using withRouter to get the location prop injected into your component.

import React, { Component } from 'react'
import { withRouter } from 'react-router'
import reactRouterFetch from 'react-router-fetch'

class App extends Component {

  state = {
    isAppFetching: false,
    appFetchingError: null
  }

  componentWillMount () {
    this.fetchRoutes(this.props)
  }

  componentWillReceiveProps (nextProps) {
    const current = `${this.props.location.pathname}${this.props.location.search}`
    const next = `${nextProps.location.pathname}${nextProps.location.search}`
    if (current === next) {
     return
    }
    this.fetchRoutes(nextProps)
  }

  shouldComponentUpdate (nextProps, nextState) {
    return !nextState.isAppFetching
  }

  fetchRoutes (props) {
    const { dispatch, location } = props
    this.setState({
      isAppFetching: true,
      appFetchingError: null
    })
    //maybe show a progress bar somewhere outside of react? go nuts!!
    reactRouterFetch(routeConfig, location, { dispatch })
      .then((results) => {
        this.setState({
          isAppFetching: false
        })
      })
      .catch((err) => {
        this.setState({
          isAppFetching: false,
          appFetchingError: err
        })
      })
  }

  render () {
    //do something with isAppFetching for the first render if single page app.
    // after the first render, the page contents will stay put until the next route's data is ready to go, so you'll have to do something outside of this.
    return (
      ...
    )
  }

}


const connectedApp = connect()(App)
export default withRouter(connectedApp)

react-router-fetch's People

Contributors

greenkeeper[bot] avatar kellyrmilligan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

papigers

react-router-fetch's Issues

An in-range update of nodemon is breaking the build 🚨

The devDependency nodemon was updated from 1.18.5 to 1.18.6.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

nodemon is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v1.18.6

1.18.6 (2018-11-05)

Bug Fixes

Commits

The new version differs by 1 commits.

  • 521eb1e fix: restart on change for non-default signals (#1409) (#1430)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml
  • Replaced the old Node.js version in your .nvmrc with the new one

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖


FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of source-map-support is breaking the build 🚨

Version 0.4.13 of source-map-support just got published.

Branch Build failing 🚨
Dependency source-map-support
Current Version 0.4.12
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As source-map-support is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this 💪


Status Details
  • continuous-integration/travis-ci/push The Travis CI build could not complete due to an error Details
Commits

The new version differs by 4 commits .

  • 1dfbc24 0.4.13
  • 4290140 Update compiled file
  • 7fdde65 Merge pull request #176 from christophehurpeau/patch-1
  • 3061a49 fix: browser regression from #169 when getResponseHeader throws

See the full diff.

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

An in-range update of react-router is breaking the build 🚨

The devDependency react-router was updated from 4.3.1 to 4.4.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

react-router is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Component updates when isAppFetching is true

Would love some help with this, been stuck for 2 days.

I am using the examples in the readme and they work fine returning the timeout promise but as soon as I add a dispatch action, the next component loads before isAppFetching is false. I checked and my dispatch is definitely returning a promise.

My code:

client.js

import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import { renderRoutes } from 'react-router-config';
import routes from '../common/config/routes';
import { BrowserRouter as Router } from 'react-router-dom';
import storeFactory from '../common/store';
import { Provider } from 'react-redux';
import { MuiThemeProvider, createMuiTheme } from 'material-ui/styles';
import th from '../common/config/theme';
import Reboot from 'material-ui/Reboot';
import '../common/sass/styles.scss';
import 'typeface-roboto';

const initialState = window.__PRELOADED_STATE__ || {};
delete window.__PRELOADED_STATE__;

const theme = createMuiTheme(th);

const store = storeFactory(initialState);

ReactDOM.hydrate(
  <Provider store={store}>
    <MuiThemeProvider theme={theme}>
      <Reboot />
      <Router>
        {renderRoutes(routes)}
      </Router>
    </MuiThemeProvider>
  </Provider>,
  document.getElementById('root')
);

App.js

import {Component} from 'react';
import {connect} from 'react-redux';
import { renderRoutes } from 'react-router-config';
import reactRouterFetch from 'react-router-fetch';
import routes from '../config/routes';

class App extends Component {

  state = {
    isAppFetching: false,
    appFetchingError: null
  }

  componentDidMount(){
    const jssStyles = document.getElementById('jss-server-side');
    if (jssStyles && jssStyles.parentNode) {
      jssStyles.parentNode.removeChild(jssStyles);
    }
    this.fetchRoutes(this.props);
  }

  componentWillReceiveProps (nextProps) {
    const current = `${this.props.location.pathname}${this.props.location.search}`;
    const next = `${nextProps.location.pathname}${nextProps.location.search}`;
    if (current === next) {
      return;
    }
    this.fetchRoutes(nextProps);
  }

  shouldComponentUpdate (nextProps, nextState) {
    console.info('Should Update', !nextState.isAppFetching);
    return false;//!nextState.isAppFetching;
  }

  fetchRoutes (props) {
    const { dispatch, location } = props;
    this.setState({
      isAppFetching: true,
      appFetchingError: null
    });

    reactRouterFetch(routes, location, { dispatch })
      .then(() => {
        this.setState({
          isAppFetching: false
        });
      })
      .catch((err) => {
        this.setState({
          isAppFetching: false,
          appFetchingError: err
        });
      });
  }

  render () {
    const {route} = this.props;
    return (
      renderRoutes(route.routes)
    );
  }
}

export default connect()(App);

Football.js

import React, {Component} from 'react';
import {fetchLeagueCountriesIfNeeded} from '../../actions';

class Football extends Component {
  static fetch (match, location, {dispatch}) {
    return dispatch(fetchLeagueCountriesIfNeeded());
  }
  render () {
    return (
      <div>Home</div>
    );
  }
}

export default Football;

An in-range update of cross-env is breaking the build 🚨

Version 3.2.0 of cross-env just got published.

Branch Build failing 🚨
Dependency cross-env
Current Version 3.1.4
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As cross-env is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this 💪


Status Details
  • continuous-integration/travis-ci/push The Travis CI build could not complete due to an error Details
Release Notes v3.2.0

<a name"3.2.0">

3.2.0 (2017-03-04)

Features

  • revamp: revamp the entire lib (backward compatible) (#63) (dad00c46)
Commits

The new version differs by 4 commits .

  • dad00c4 feat(revamp): revamp the entire lib (backward compatible) (#63)
  • e33a85c docs(README): Add doc for cross-var. (#58)
  • 5e590ec docs(README): added how to use cross-env to run npm sub-scripts (#53)
  • afdb2de docs(README): mention Bash on Windows (#49)

See the full diff.

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

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.