Skip to content

Commit

Permalink
fix: fundamental Switch state doesn't refresh (#1193)
Browse files Browse the repository at this point in the history
  • Loading branch information
rjstyles committed Sep 1, 2020
1 parent a9047cf commit 1a7ac92
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/Switch/Switch.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import FormLabel from '../Forms/FormLabel';
import keycode from 'keycode';
import PropTypes from 'prop-types';
import SwitchItem from './_SwitchItem';
import React, { useCallback, useState } from 'react';
import React, { useCallback, useEffect, useState } from 'react';
import 'fundamental-styles/dist/icon.css';
import 'fundamental-styles/dist/switch.css';

Expand All @@ -31,6 +31,10 @@ const Switch = React.forwardRef(({

let [isChecked, setIsChecked] = useState(!!checked);

useEffect(() => {
setIsChecked(!!checked);
}, [checked]);

const handleChange = (e) => {
setIsChecked(!isChecked);
onChange(e);
Expand Down
24 changes: 24 additions & 0 deletions src/Switch/Switch.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,28 @@ describe('<Switch />', () => {
).toBe('Sample');
});
});

describe('Switch state change on props update', () => {
const wrapper = mount(<Switch checked />);

test('should change to not checked state if new props are sent with checked as false', () => {
//updating prop to checked as false
wrapper.setProps({ checked: false });
wrapper.update();

// check that switch is not checked
expect(wrapper.find('input').props().checked).toBe(false);
expect(wrapper.find('input').props()['aria-checked']).toBe(false);
});

test('should change to checked state if new props are sent with checked as true', () => {
//updating prop to checked as true
wrapper.setProps({ checked: true });
wrapper.update();

// check that switch is checked
expect(wrapper.find('input').props().checked).toBe(true);
expect(wrapper.find('input').props()['aria-checked']).toBe(true);
});
});
});

0 comments on commit 1a7ac92

Please sign in to comment.