Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

VSCodeCheckbox onChange handler called on first render #408

Open
deerob4 opened this issue Sep 22, 2022 · 2 comments
Open

VSCodeCheckbox onChange handler called on first render #408

deerob4 opened this issue Sep 22, 2022 · 2 comments
Assignees
Labels
bug Something isn't working

Comments

@deerob4
Copy link

deerob4 commented Sep 22, 2022

Describe the bug

VSCodeCheckbox React components that have a checked value which references a React state variable initialised to true will call their onChange prop on first render. Since the onChange prop is usually toggling that same state variable, the component enters into an infinite recursive loop.

This actually seems to happen when useState is initialised with anything other than false. I tried a bunch of other values, truthy and falsy, and they all triggered the bug. It doesn't occur when the checked prop has a literal value of true.

To reproduce

The problem can be reproduced with the following code:

import React, { FunctionComponent, useState } from "react";
import { VSCodeCheckbox } from "@vscode/webview-ui-toolkit/react";

const MyPage: FunctionComponent = () => {
  const [isChecked, setIsChecked] = useState(true);

  function toggleChecked() {
    console.log("I'll be called on first render");
    setIsChecked(checked => !checked)
  }

  return (
    <VSCodeCheckbox onChange={toggleChecked} checked={isChecked}>
      Toggle checked
    </VSCodeCheckbox>
  );
};

Expected behavior

The onChange handler should only be called when the checkbox is first clicked, like normal <input type="checkbox" /> elements.

Current behavior

The onChange handler is called immediately on first render, which results in an infinite loop if it toggles the value read by checked.

Desktop (please complete the following information):

  • OS Version: macOS 12.6
  • Toolkit Version: v1.1.0
@deerob4 deerob4 added the bug Something isn't working label Sep 22, 2022
@kevin-s-wang
Copy link

kevin-s-wang commented Sep 23, 2022

I've also encountered such an issue, the component keeps re-rendering util its max-depth when triggered onChanged event.
So I had to write the radio buttons using raw HTML.

@hawkticehurst
Copy link
Member

Thanks again for the bug report @deerob4!

Like I said in your other issue, I've been a bit busy with other work but will also put this on the top of my todo list once I have some free cycles 😊

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

3 participants