javascript - React - input checkbox onchange won't fire first time - Stack Overflow

The behaviour of a checkbox input is not being very reliable.I'm setting the state of a checkbox

The behaviour of a checkbox input is not being very reliable.

I'm setting the state of a checkbox based on state from the store. This works fine. However sometimes checking the checkbox will not fire the onchange. Checking the box a second time will fire, however the UI will display the wrong state as it misfired the first time.

I'm using NextJS. This mostly happens when loading the page for the first time, or hard refresh.

import { useDispatch, useSelector } from 'react-redux';
import _cloneDeep from 'lodash/cloneDeep';

export default function Privacy() {
    const consentObj = useSelector((state) => state.cookieOptions);
    const dispatch = useDispatch();

    const analyticsConsent = useSelector(
        (state) => state.cookieOptions.analytics
    );

    function toggleConsentAnalytics() {
        // this function will not fire on first input onchange
        const newSettings = _cloneDeep(consentObj);
        newSettings.analytics = !consentObj.analytics;

        dispatch({ type: 'SET_COOKIE_OPTIONS', payload: newSettings });
    }

    return (
        <div>
            <div className={css.settingContainer}>
                <strong>Analytics cookie</strong>
                <label>
                    <div className={css.switchWrap}>
                        {analyticsConsent ? 'On' : 'Off'}
                        <span className={css.switch}>
                            <input
                                defaultChecked={analyticsConsent}
                                onChange={() => toggleConsentAnalytics()}
                                type="checkbox"
                            />
                            <span className={css.slider}></span>
                        </span>
                    </div>
                </label>
            </div>
        </div>
    );
}

I've removed what I think is irrelevant code from my example.

I have an identical flow using a Class ponent and it works as expected. But it seems that we should be moving away from this into functional ponents so would very much like to solve this rather than revert to a Class!

Thanks in advance for any assistance

The behaviour of a checkbox input is not being very reliable.

I'm setting the state of a checkbox based on state from the store. This works fine. However sometimes checking the checkbox will not fire the onchange. Checking the box a second time will fire, however the UI will display the wrong state as it misfired the first time.

I'm using NextJS. This mostly happens when loading the page for the first time, or hard refresh.

import { useDispatch, useSelector } from 'react-redux';
import _cloneDeep from 'lodash/cloneDeep';

export default function Privacy() {
    const consentObj = useSelector((state) => state.cookieOptions);
    const dispatch = useDispatch();

    const analyticsConsent = useSelector(
        (state) => state.cookieOptions.analytics
    );

    function toggleConsentAnalytics() {
        // this function will not fire on first input onchange
        const newSettings = _cloneDeep(consentObj);
        newSettings.analytics = !consentObj.analytics;

        dispatch({ type: 'SET_COOKIE_OPTIONS', payload: newSettings });
    }

    return (
        <div>
            <div className={css.settingContainer}>
                <strong>Analytics cookie</strong>
                <label>
                    <div className={css.switchWrap}>
                        {analyticsConsent ? 'On' : 'Off'}
                        <span className={css.switch}>
                            <input
                                defaultChecked={analyticsConsent}
                                onChange={() => toggleConsentAnalytics()}
                                type="checkbox"
                            />
                            <span className={css.slider}></span>
                        </span>
                    </div>
                </label>
            </div>
        </div>
    );
}

I've removed what I think is irrelevant code from my example.

I have an identical flow using a Class ponent and it works as expected. But it seems that we should be moving away from this into functional ponents so would very much like to solve this rather than revert to a Class!

Thanks in advance for any assistance

Share Improve this question asked Mar 29, 2021 at 11:13 bjurtownbjurtown 1734 silver badges13 bronze badges 5
  • 1 try using onClick instead – Tiago Coelho Commented Mar 29, 2021 at 11:15
  • 1 I've removed what I think is irrelevant code from my example....can you make a minimum stackblitz that reproduces your behavior? – Adam Jenkins Commented Mar 29, 2021 at 11:18
  • 1 Can you verify that analyticsConsent is never undefined upon first render. Try to console.log it – Domino987 Commented Mar 29, 2021 at 11:19
  • @Domino987 it looks like to begin with the state is loaded with the default state, the loads the actual current state. – bjurtown Commented Mar 29, 2021 at 11:39
  • @TiagoCoelho This actually worked. if you make it an answer I'll be happy to select it as the correct one – bjurtown Commented Mar 29, 2021 at 11:40
Add a ment  | 

1 Answer 1

Reset to default 7

You can use onClick instead of onChange and it will work properly.

This has nothing to do with react, but with how the onchange event works in html.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744136669a4560091.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信