Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: stop double render on a route change #13

Merged
merged 7 commits into from
Jan 29, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions flow-typed/beforeComponent_vx.x.x.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,11 @@ declare module 'Before.component' {
entries?: Array<LocationType>
};

declare type SwitchRoutesProps = {
+data: ?DataType,
+routes: Array<AsyncRoute>
};

declare type Match = {
params: { [key: string]: ?string },
isExact: boolean,
Expand All @@ -132,8 +137,7 @@ declare module 'Before.component' {
|};

declare type BeforeState = {
previousLocation: ?LocationType,
data: ?DataType
data: { [key: string]: any }
};

declare type StaticRouterContext = {
Expand Down
38 changes: 20 additions & 18 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,56 +46,56 @@
"@babel/core": "^7.2.0",
"@babel/plugin-external-helpers": "^7.2.0",
"@babel/preset-flow": "^7.0.0",
"@babel/runtime": "^7.2.0",
"@babel/runtime": "^7.3.1",
"@commitlint/config-conventional": "^7.3.1",
"@flybondi/rollup-plugin-ramda": "^1.0.0",
"@loadable/component": "^5.2.2",
"@loadable/server": "^5.3.0",
"@loadable/component": "^5.5.0",
"@loadable/server": "^5.5.0",
"babel-core": "^7.0.0-0",
"babel-eslint": "^10.0.1",
"babel-jest": "^23.6.0",
"babel-jest": "^24.0.0",
"babel-preset-react-app": "^7.0.0",
"commitlint": "^7.3.2",
"cross-env": "^5.2.0",
"enzyme": "^3.8.0",
"enzyme-adapter-react-16": "^1.7.1",
"eslint": "^5.12.0",
"eslint-config-prettier": "^3.4.0",
"enzyme-adapter-react-16": "^1.8.0",
"eslint": "^5.12.1",
"eslint-config-prettier": "^4.0.0",
"eslint-config-standard": "^12.0.0",
"eslint-plugin-flowtype": "^3.2.1",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-import": "^2.15.0",
"eslint-plugin-node": "^8.0.1",
"eslint-plugin-prettier": "^3.0.1",
"eslint-plugin-promise": "^4.0.1",
"eslint-plugin-ramda": "^2.5.1",
"eslint-plugin-react": "^7.12.3",
"eslint-plugin-react": "^7.12.4",
"eslint-plugin-standard": "^4.0.0",
"flow-bin": "0.90.0",
"flow-bin": "0.91.0",
"flow-typed": "^2.5.1",
"husky": "^1.3.1",
"jest": "^23.6.0",
"jest": "^24.0.0",
"lint-staged": "^8.1.0",
"npm-run-all": "^4.1.5",
"object-assign": "^4.1.1",
"prettier": "^1.15.3",
"prettier": "^1.16.1",
"raf": "^3.4.1",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"react-helmet": "^5.2.0",
"react-router-dom": "^4.3.1",
"rollup": "^1.1.0",
"rollup": "^1.1.2",
"rollup-plugin-analyzer": "^3.0.0",
"rollup-plugin-babel": "^4.3.0",
"rollup-plugin-bundle-size": "^1.0.2",
"rollup-plugin-babel": "^4.3.2",
"rollup-plugin-bundle-size": "^1.0.3",
"rollup-plugin-clean": "^1.0.0",
"rollup-plugin-commonjs": "^9.2.0",
"rollup-plugin-filesize": "^6.0.0",
"rollup-plugin-filesize": "^6.0.1",
"rollup-plugin-flow": "^1.1.1",
"rollup-plugin-node-resolve": "^4.0.0",
"rollup-plugin-progress": "^1.0.0",
"rollup-plugin-visualizer": "^0.9.2",
"run-sequence": "^2.2.1",
"webpack": "^4.28.4",
"webpack": "^4.29.0",
"whatwg-fetch": "^3.0.0"
},
"lint-staged": {
Expand Down Expand Up @@ -129,7 +129,9 @@
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"
],
"setupTestFrameworkScriptFile": "<rootDir>/config/enzyme.config.js",
"setupFilesAfterEnv": [
"<rootDir>/config/enzyme.config.js"
],
"testEnvironment": "node",
"moduleNameMapper": {
"\\.css$": "identity-obj-proxy"
Expand Down
50 changes: 26 additions & 24 deletions src/Before.component.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,28 @@ import type {
BeforeState,
BeforeComponentWithRouterProps,
DataType,
FixMeType
FixMeType,
SwitchRoutesProps
} from 'Before.component';
import React, { Component } from 'react';
import React, { Component, memo } from 'react';
import { Switch, Route, withRouter, type ContextRouter } from 'react-router-dom';
import { getInitialPropsFromComponent } from './fetchInitialPropsFromRoute';
import { isClientSide } from './utils';
import { converge, find, nthArg, pipe, propEq } from 'ramda';
import { parse } from 'query-string';
const { NODE_ENV } = process.env;

const Routes = memo(({ routes, data }: SwitchRoutesProps) =>
routes.map((route, index) => (
<Route
key={`route--${index}`}
path={route.path}
render={createRenderRoute(data, route.component)}
exact={route.exact}
/>
))
);

/**
* Log the error to console only in development environment and throw up given error;
* @param {Error} error
Expand All @@ -35,6 +47,7 @@ const createRenderRoute = (initialData: ?DataType, Component: FixMeType) => (
) => {
const routeProps = {
...initialData,
isFetchingInitialProps: initialData === undefined,
history: props.history,
location: props.location,
match: {
Expand Down Expand Up @@ -70,8 +83,7 @@ const getCurrentRouteByPath: (
*/
export class Before extends Component<BeforeComponentWithRouterProps, BeforeState> {
state = {
previousLocation: this.props.location,
data: this.props.data
data: { [this.props.location.pathname]: this.props.data }
};

fetchInitialPropsFromCurrentRoute = async (props: BeforeComponentWithRouterProps) => {
Expand All @@ -88,15 +100,13 @@ export class Before extends Component<BeforeComponentWithRouterProps, BeforeStat
...rest
});
return {
previousLocation: location,
data
data: { [pathname]: data }
};
}
} catch (error) {
throwError(error);
return {
previousLocation: null,
data: null
data: {}
};
}
};
Expand All @@ -109,28 +119,20 @@ export class Before extends Component<BeforeComponentWithRouterProps, BeforeStat
}

shouldComponentUpdate(nextProps: BeforeComponentWithRouterProps, nextState: BeforeState) {
return nextState.previousLocation !== null;
// NOTE(lf): Allow render only when the routes change or the data in the state has changed.
return this.props.location !== nextProps.location || this.state.data !== nextState.data;
}

getData(path: string) {
return isClientSide() ? this.state.data : this.props.data;
getData(pathname: string) {
return isClientSide() ? this.state.data[pathname] : this.props.data;
}

render() {
const { previousLocation } = this.state;
const { location, routes } = this.props;
const loc = previousLocation || location;
const initialData = this.getData(loc.pathname);
const { routes, location } = this.props;
const initialData = this.getData(location.pathname);
return (
<Switch location={loc}>
{routes.map((route, index) => (
<Route
key={`route--${index}`}
path={route.path}
render={createRenderRoute(initialData, route.component)}
exact={route.exact}
/>
))}
<Switch location={location}>
<Routes routes={routes} data={initialData} />
</Switch>
);
}
Expand Down
53 changes: 49 additions & 4 deletions src/Before.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,26 @@
*/

import React from 'react';
import Before from './Before.component';
import BeforeComponent, { Before } from './Before.component';
import { StaticRouter, Switch } from 'react-router-dom';
import { mount } from 'enzyme';
import { mount, shallow } from 'enzyme';

// NOTE(lf): work around until React.memo is fully supported by Jest (https://github.com/airbnb/enzyme/issues/1875)
jest.mock('react', () => {
const r = jest.requireActual('react');
return { ...r, memo: x => x };
});

jest.mock('./utils', () => {
const { T } = jest.requireActual('ramda');
return {
isClientSide: T
};
});

afterAll(() => {
jest.resetModules();
});

test('the rendered component should have a Route component', () => {
const DummyComponent = () => <span>Hi there!</span>;
Expand All @@ -24,13 +41,41 @@ test('the rendered component should have a Route component', () => {
};
const wrapper = mount(
<StaticRouter location="/" context={context}>
<Before {...beforeProps} />
<BeforeComponent {...beforeProps} />
</StaticRouter>
);
const route = wrapper.find(Switch).childAt(0);
const routes = wrapper.find(Switch).childAt(0);
const route = routes.childAt(0);

expect(wrapper.find(Switch).props().location).toHaveProperty('pathname', '/');
expect(wrapper.find(Switch).children()).toHaveLength(1);
expect(route.key()).toEqual('route--0');
expect(route.props().path).toEqual('/');
expect(route.props().exact).toBeTruthy();
});

test('fetch initial props from current route component', () => {
const getInitialProps = jest.fn().mockReturnValue({ name: 'DummyComponent' });
const DummyComponent = () => <span>Hi there!</span>;
DummyComponent.getInitialProps = getInitialProps;

const beforeProps = {
location: {
pathname: '/'
},
routes: [
{
path: '/',
component: () => <span>Hi there!</span>
},
{
path: '/props',
component: DummyComponent
}
],
data: {}
};
const wrapper = shallow(<Before {...beforeProps} />);
wrapper.setProps({ location: { pathname: '/props' } });
expect(getInitialProps).toHaveBeenCalled();
});
Loading