Skip to content
This repository has been archived by the owner on Apr 13, 2023. It is now read-only.

Support getDerivedStateFromProps #2076

Merged
merged 6 commits into from
Jun 26, 2018
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
2 changes: 2 additions & 0 deletions Changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
- The `ApolloProvider` `children` prop type has been changed from `element`
to `node`, to allow multiple children.
- [@quentin-](https://github.com/quentin-) in [#1955](https://github.com/apollographql/react-apollo/pull/1955)
- Properly support the new `getDerivedStateFromProps` lifecycle method.
- [@amannn](https://github.com/amannn) in [#2076](https://github.com/apollographql/react-apollo/pull/2076)

## 2.1.6 (June 19, 2018)

Expand Down
8 changes: 7 additions & 1 deletion src/getDataFromTree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ export function walkTree(
// In case the user doesn't pass these to super in the constructor
instance.props = instance.props || props;
instance.context = instance.context || context;

// Set the instance state to null (not undefined) if not set, to match React behaviour
instance.state = instance.state || null;

Expand All @@ -93,7 +94,12 @@ export function walkTree(
instance.state = Object.assign({}, instance.state, newState);
};

if (instance.componentWillMount) {
if (Comp.getDerivedStateFromProps) {
const result = Comp.getDerivedStateFromProps(instance.props, instance.state);
if (result !== null) {
instance.state = Object.assign({}, instance.state, result);
}
} else if (instance.componentWillMount) {
instance.componentWillMount();
}

Expand Down
30 changes: 30 additions & 0 deletions test/client/getDataFromTree.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,36 @@ describe('SSR', () => {
expect(elementCount).toEqual(7);
});

it('basic classes with getDerivedStateFromProps', () => {
const renderedCounts: Number[] = [];
class MyComponent extends React.Component<any> {
state = { count: 0 };

static getDerivedStateFromProps(nextProps: any, prevState: any) {
if (nextProps.increment) {
return { count: prevState.count + 1 };
}
return null;
}

componentWillMount() {
throw new Error(
"`componentWillMount` shouldn't be called when " +
'`getDerivedStateFromProps` is available',
);
}

render() {
renderedCounts.push(this.state.count);
return <div>{this.state.count}</div>;
}
}
walkTree(<MyComponent increment />, {}, () => {
// noop
});
expect(renderedCounts).toEqual([1]);
});

it('basic classes with React 16.3 context', () => {
if (!React.createContext) {
// Preact doesn't support createContext yet, see https://github.com/developit/preact/pull/963
Expand Down