0

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

<div key={prod && prod.id}>
                        <button
                          onClick={updateProducts}
                          value={prod && prod.id}
                        >
                          Edit
                        </button>
                      </div>
  • Looks like your useState is lagging one step behind. This could help: https://stackoverflow.com/questions/62994853/react-hooks-setstate-lagging-one-step-behind – Y H R Dec 31 '21 at 18:33

1 Answers1

1

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);
  };
Nathan
  • 949
  • 8
  • 19