cca-io / rescript-mui

ReScript bindings for MUI
MIT License
255 stars 52 forks source link

`Any`type does not seem to work with variants #117

Closed keuhdall closed 3 years ago

keuhdall commented 4 years ago

Hello,

I've been trying to create a little form using the components FormControl, RadioGroup and FormControlLabel, however I came across a what seem to be a little bug.

In my code, I created the following types:

type answer = Yes | No;
type state = {
  questionIndex: int,
  questionAnswer: answer
};

This initial state:

  let (state, setState) = React.useState(() => {
    questionIndex: 0,
    questionAnswer: Yes
  });

And this RadioGroup:

    <RadioGroup name="answer" row=true value=Any(state.questionAnswer) onChange=(e => {
        let value = e->ReactEvent.Form.target##value
        setState(s => {...s, questionAnswer: value})
      })>
      <FormControlLabel value=Any(Yes) control={<Radio />} label=mkRadioLabel("Yes") />
      <FormControlLabel value=Any(No) control={<Radio />} label=mkRadioLabel("No") />
    </RadioGroup>

When doing this, the radio button is toggled on "Yes" just as expected, but it disappears as soon as I click on one of the 2 radio buttons. However, if in my state I change the type of questionAnswer from answer to string (and accordingly in the rest of the code), it works perfectly.

Is it the expected behavior, or is this indeed a bug ?

fhammerschmidt commented 3 years ago

Variants get compiled to numbers when they have no payload. This may result in unintended consequences. But you can implement your example easily with the help of polymorphic variants which get compiled to strings.

Just change the answer type to

type answer = [ #Yes | #No ]

and update the rest of the code accordingly.

Sorry for the late answer, but I wasn't even maintaining this project back then. Maybe it will help other users. I will add an example in the same vein as your code.