Skip to content

Commit

Permalink
Editable tags: Update state when props change, fixes #41
Browse files Browse the repository at this point in the history
see 6775f3b for further details
  • Loading branch information
Tobias Schmidt committed Apr 30, 2018
1 parent 231a0aa commit 2f3a68c
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 6 deletions.
28 changes: 22 additions & 6 deletions src/components/tagsEditable/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,8 @@ export default class TagsEditable extends Component {
this.handleBlur = this.handleBlur.bind(this);

this.state = {
tags: props.tags.map(tag => {
return { id: null, name: tag };
}),
suggestions: props.suggestions.map(tag => {
return { id: null, name: tag };
})
tags: this.formatTags(props.tags),
suggestions: this.formatTags(props.suggestions)
};
}

Expand All @@ -27,6 +23,15 @@ export default class TagsEditable extends Component {
suggestions: PropTypes.array
};

/**
* Format tags to match react-tags-autocomplete format
*
* @param {Array} tags flat array
*
* @return {Array.<Object>} formatted array with objects
*/
formatTags = tags => tags.map(tag => ({ id: null, name: tag }));

handleTagDelete(i) {
const { state, props } = this;

Expand Down Expand Up @@ -78,6 +83,17 @@ export default class TagsEditable extends Component {
);
}

componentWillReceiveProps(nextProps) {
// copy tag props to state on update
if (nextProps.tags !== this.props.tags) {
this.setState({ tags: this.formatTags(nextProps.tags) });
}
// copy suggestion props to state on update
if (nextProps.suggestions !== this.props.suggestions) {
this.setState({ suggestions: this.formatTags(nextProps.suggestions) });
}
}

render(props) {
// TODO nicer style classes
const classNames = {
Expand Down
32 changes: 32 additions & 0 deletions src/components/tagsEditable/tests/index.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { h } from 'preact';
import TagsEditable from '../index.js';
import { shallow } from 'preact-render-spy';

const testTags1 = ['a', 'b', 'c'];
const testTags2 = ['a', 'd', 'c', 'f'];

const testSuggestions1 = ['suggestion', 12341, 'other suggestion'];
const testSuggestions2 = ['more ', 'more', 'test'];

describe('Test that data is copied from props to state', () => {
const context = shallow(
<TagsEditable
classNames={{ selectedTag: 'a' }}
suggestions={testSuggestions1}
tags={testTags1}
/>
);
test('State should match the props', () => {
expect(context.state('tags').map(tag => tag.name)).toEqual(testTags1);
});
test('State should update when props change', () => {
context.render(
<TagsEditable
classNames={{ selectedTag: 'a' }}
suggestions={testSuggestions2}
tags={testTags2}
/>
);
expect(context.state('tags').map(tag => tag.name)).toEqual(testTags2);
});
});

0 comments on commit 2f3a68c

Please sign in to comment.