Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Onclick function getting the correct data after the second click

I am trying to get a single product detail whenever I click on the button, but I get the wrong product detail on the first click, then get the correct product detail on the second click

  const updateProducts = async (e) => {
    const singleProduct = await axios.get(
      `https://middlemen-backend.herokuapp.com/api/product/${id}`
    );
    console.log(singleProduct);
    setproductDetails(singleProduct);
    setid(e.target.value);
    setopenModal(true);
  };

The state for the id and the single product detail

 const [productDetails, setproductDetails] = useState({});
 const [id, setid] = useState(1);

below is the onclick button to get the single data

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div key={prod && prod.id}>
                        <button
                          onClick={updateProducts}
                          value={prod && prod.id}
                        >
                          Edit
                        </button>
                      </div>

>Solution :

You’re setting the id state after the axios request. You should also just use the e.target.value as the URL param:

  const updateProducts = async (e) => {
   const idValue = e.target.value;

   setid(idValue);

    const singleProduct = await axios.get(
      `https://middlemen-backend.herokuapp.com/api/product/${idValue}`
    );
    console.log(singleProduct);
    setproductDetails(singleProduct);
    
    setopenModal(true);
  };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading