hperrin / svelte-material-ui

Svelte Material UI Components
https://sveltematerialui.com/
Apache License 2.0
3.31k stars 285 forks source link

`Switch` has to be clicked twice to change its state when changing change in an `on:click` function #545

Closed DetachHead closed 1 year ago

DetachHead commented 1 year ago

Describe the bug i'm attempting to handle the state of a Switch element in an on:click function, as i'm not able to use bind in my case. however the on:click function seems to be causing the switch to behave incorrectly, and i can't figure out why.

To Reproduce

<script lang="ts">
    import { MDCSwitch } from '@material/switch'
    import FormField from '@smui/form-field'
    import Switch from '@smui/switch'

    export let checked: boolean = false

    const changeBooleanValue = (event: CustomEvent<unknown>) => {
        const switchElement = new MDCSwitch(event.currentTarget as HTMLButtonElement)
        console.log(
            `the switch was ${switchElement.selected}, and the state says that is was ${checked}`,
        )
        if (checked == switchElement.selected) {
            console.log(`now I am updating the state to ${!switchElement.selected}`)
            checked = !switchElement.selected
        } else {
            console.log('didnt change')
        }
    }
</script>

<FormField align="end">
    <Switch {checked} on:click={(e) => changeBooleanValue(e)} />
</FormField>

Expected behavior switch behaves normally

Screenshots

Desktop (please complete the following information):

DetachHead commented 1 year ago

nvm using on:SMUISwitch:change works