How to update the latest value to the Radio button component using Radix UI

34 Views Asked by At

I have a form created using Radix UI. In that I have radio button options True or false.

I am trying to edit a form and for that I am using a API call.

Based on the call, results for that radio button values True or False or Empty

I need to show the radio button as True if API value is true and vice versa.

I am trying to set the default value to radio button.

But its not updating the latest value.

Its setting the initial value only. That is empty. So none of the radio buttons are selected. For that specific case, it needs to be true. But its not updating in UI

function MyComponent() {
  const [selectedExpectedValue, setSelectedExpectedValue] = useState<string>("");
  useEffect(() => {
    fetch(`/api/postings/id=3`)
      .then((response) => response.json())
      .then((postingFormData) => {
        setPosting(postingFormData.data);
        setPostingTitle(postingFormData.data.title);
        setPostingBody(postingFormData.data.body);

        // Assuming test.Employer is a constant or enum value
        if (test === test.Employer && postingFormData.data.expected_a !== "") {
          setSelectedExpectedValue(postingFormData.data.expected_a);
        }
      });
  }, [postingId, test]);

  return (
    <RadioGroup.Root
      className="flex gap-2.5"
      aria-label="expectedValueA"
      required={true}
      id="expectedValueA"
      name="expectedValueA"
      defaultValue={selectedExpectedValue}
    >
      {expectedValueBoolean.map((option, index) => (
        <div key={index} className="flex items-center mx-4">
          <Form.Control asChild>
            <RadioGroup.Item
              className="bg-white w-5 h-5 rounded-full hover:border-inherit focus:border-blue-400 hover:ring-4 focus:shadow-[0_0_0_2px] border border-solid border-slate-600 focus:shadow-transparent outline-none cursor-default"
              value={option.value}
              id={option.label.toLowerCase()}
            >
              <RadioGroup.Indicator className="flex items-center justify-center w-full h-full relative after:content-[''] after:block after:w-[11px] after:h-[11px] after:rounded-[50%] after:bg-blue-500" />
            </RadioGroup.Item>
          </Form.Control>

          <label
            className="text-black text-[15px] leading-none pl-[15px]"
            htmlFor={option.label.toLowerCase()}
          >
            {option.label}
          </label>
        </div>
      ))}
    </RadioGroup.Root>
  );
}

0

There are 0 best solutions below