Skip to content

Commit

Permalink
feat(ResourceTable): Trigger re-fetch when rel, name or `embedded…
Browse files Browse the repository at this point in the history
…` props change
  • Loading branch information
wms committed Sep 27, 2017
1 parent 3019617 commit 620f5eb
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 6 deletions.
57 changes: 56 additions & 1 deletion src/components/ResourceTable.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ describe('default behaviour', () => {
});
});

describe('when columns prop changes', () => {
describe('when `columns` prop changes', () => {
it('fetches with new params', () => {
fetch.mockClear();

Expand Down Expand Up @@ -150,6 +150,61 @@ describe('default behaviour', () => {
expect(fetch).not.toHaveBeenCalled();
});
});

describe('when `rel` prop changes', () => {
it('fetches with new rel', () => {
fetch.mockClear();

root.setProps({
rel: 'users'
});

expect(fetch).toHaveBeenCalledWith(({
rel: 'users'
}), ({
where: undefined,
order: undefined,
page: undefined
}));
});
});

describe('when `name` prop changes', () => {
it('fetches with new rel', () => {
fetch.mockClear();

root.setProps({
name: 'item'
});

expect(fetch).toHaveBeenCalledWith(({
rel: 'widgets',
name: 'item'
}), ({
where: undefined,
order: undefined,
page: undefined
}));
});
});

describe('when `embedded` prop changes', () => {
it('fetches again (although not really necessary)', () => {
fetch.mockClear();

root.setProps({
embedded: 'something-else'
});

expect(fetch).toHaveBeenCalledWith(({
rel: 'widgets'
}), ({
where: undefined,
order: undefined,
page: undefined
}));
});
});
});

describe('when `name` is specified', () => {
Expand Down
21 changes: 16 additions & 5 deletions src/components/ResourceTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -115,11 +115,24 @@ export class ResourceTable extends React.PureComponent<Props, State> {
}

componentWillReceiveProps(nextProps: Props) {
const params = this._nextParams(nextProps);
let shouldFetch = (
(nextProps.rel !== this.props.rel) ||
(nextProps.name !== this.props.name) ||
// @todo: Changing 'embedded' should not trigger a re-fetch
(nextProps.embedded !== this.props.embedded)
);

let params: any = this._nextParams(nextProps);

if (params) {
this.setState({ params });
this.fetch(params);
shouldFetch = true;
} else {
params = this.state.params;
}

if (shouldFetch) {
this.fetch(params, nextProps);
}
}

Expand All @@ -137,9 +150,7 @@ export class ResourceTable extends React.PureComponent<Props, State> {
}
}

fetch = (params = this.state.params) => {
const { resource, rel, name, embedded } = this.props;

fetch = (params = this.state.params, { resource, rel, name, embedded } = this.props) => {
this.setState({ loading: true });

const link = name ?
Expand Down

0 comments on commit 620f5eb

Please sign in to comment.