Skip to content

Commit

Permalink
feat: 🎸 Added callback functions to setState and setProps (#100)
Browse files Browse the repository at this point in the history
* feat: 🎸 Added callback functions to setState and setProps

Added callback functions to setState and setProps function which receive
current widget.state and widget props as their first argument. This is
in addition to the old api, when an object is provided as a argument to
setState/setProps function, it works the same way as before. Only
function types are handled differently.

* test: 💍 Fixed tests
  • Loading branch information
jsimck authored Aug 27, 2021
1 parent 111fda7 commit 2bbee18
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
22 changes: 22 additions & 0 deletions packages/plugin-component/src/__tests__/indexSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,17 @@ describe('component plugin API', () => {
expect(widget.state.name).toEqual('black');
});

it('should allow setting new widget state using fn callback', async () => {
await widget.mount();
await widget.setState({ name: 'black' });

let setState = jest.fn((state) => ({ name: state.name + ' surname' }));
await widget.setState(setState);

expect(widget.state.name).toEqual('black surname');
expect(setState).toHaveBeenCalledWith({ name: 'black' });
});

it('should call life cycle update method', async () => {
widget.update = jest.fn();

Expand All @@ -225,6 +236,17 @@ describe('component plugin API', () => {
expect(widget.props.name).toEqual('black');
});

it('should allow setting new widget props using fn callback', async () => {
await widget.mount();
await widget.setProps({ name: 'black' });

let setProps = jest.fn((props) => ({ name: props.name + ' surname' }));
await widget.setProps(setProps);

expect(widget.props.name).toEqual('black surname');
expect(setProps).toHaveBeenCalledWith({ name: 'black' });
});

it('should call life cycle update method', async () => {
widget.update = jest.fn();

Expand Down
18 changes: 14 additions & 4 deletions packages/plugin-component/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,23 @@ function componentAPI() {

return callLifeCycleMethod(widget, 'update', args);
},
async setState(widget, state) {
widget.state = { ...widget.state, ...state };
async setState(widget, stateSetter) {
widget.state = {
...widget.state,
...(typeof stateSetter === 'function'
? stateSetter(widget.state)
: stateSetter),
};

return widget.update();
},
async setProps(widget, props) {
widget.props = { ...widget.props, ...props };
async setProps(widget, propsSetter) {
widget.props = {
...widget.props,
...(typeof propsSetter === 'function'
? propsSetter(widget.props)
: propsSetter),
};

if (!widget.$in.component.isMounted) {
return;
Expand Down

0 comments on commit 2bbee18

Please sign in to comment.