Search code examples
reactjsradio-button

defaultChecked on multiple mapped buttons and need to click twice to render


i'm mapping multiple buttons and want to select the 1st button to be checked on render and that value is shown on render

this is the axios get

const [productData, setProductData] = useState([]);
const [size, setSize] = useState([]);
const [choice, setChoice] = useState("");

useEffect(() => {
const checkId = parseInt(window.location.href.slice(-1));
axios.get(`http://localhost:5000/products?id=${checkId}`)
.then((response) => {
setProductData(response.data[0]);
setSize(response.data[0].size);
setChoice(response.data[0].size[0].calories);
});
}, []);

here is the button map

const GetSize = () => {
    return size.map((val, i) => {
      return (
        <>
          <div>
            <input
              onClick={(e) => {
                setChoice(val.calories);
              }}
              defaultChecked={i == 0}
              type="radio"
            />
            <p>{val.option}</p>
            <p>{val.cup}</p>
          </div>
        </>
      );
    });
  };

and have to show a value on render here

 <div >
     <h1>{choice === 0 ? "" : choice}</h1
    <div>
       <h1>Size options</h1>
    </div>
    <div >
       <form>
          <GetSize />
        </form>
    </div>
</div>

on render the {choice} doesn't show and only shown whenever i clicked on the radio button.

how do i make it so {choice} waits until setChoice runs

and also, the button needs to be clicked twice for it to be rendered chosen, but one click on the button is enough to make {choice} rendered


Solution

  • possible solution for the first part of the question

    useEffect(() => {
    
       const checkId = parseInt(window.location.href.slice(-1));
       axios.get(`http://localhost:5000/products?id=${checkId}`)
       .then((response) => {
              setProductData(response.data?.[0] ?? []);
              const responseSize = response.data?.[0]?.size ?? []
              setSize(responseSize);
              // setting the default choice
              setChoice(responseSize.[0]?.calories ?? "")
       });
    
    }, []);