[Fixed] Fetch POST request runs randomly without triggering the function

Issue

Im working with reactjs, express and postgresql app where there is 3 icons if one of them clicked it will send value to database according which icon clicked, yes its worked if clicked the icon, the value successfully sent to the database, but in the next 3-5 minutes i check my database, there is 2-3 more unwanted value added according my last click and throws error on the console. as the picture below, the value at 07.43 below is value added by triggering the function, and at 07.45 is value added randomly without triggering the function

enter image description here

The first value is added in the right way, the seccond one at 7.45 is added without im triggering the function

here is my code for the icon

<img
    src={goodIcon}
    alt='Bad'
    onClick={onClickGood}
    className='rating__container__icon'
/>

Here is my onClick method to fetch post to database

const onClickGood = async (e) => {
        e.preventDefault();
        try {
            const body = { good };
            const response = await fetch('http://localhost:5555/good-rating', {
                method: 'POST',
                headers: { 'content-type': 'application/json' },
                body: JSON.stringify(body),
            });
            console.log(response);
        } catch (error) {
            console.error(error.message);
        }
    };

And here is my code for the backend to handle that post request above

router.post('/good-rating', (req, res) => {
    try {
        const { good } = req.body;
        pool.query(
            'INSERT INTO ratings (good_rating) VALUES ($1) RETURNING *',
            [good]
        );
    } catch (error) {
        console.error(err.message);
        res.status(500).send('Oops, Something Went Wrong!');
    }
});

what i’ve been done is changed the onclick fetch method from try-catch to promise, wrapped the icons with tag form and changed to button type.

Solution

in the backend need to send back response when is success or failed

router.post('/good-rating', (req, res) => {
try {
    const { good } = req.body;
    pool.query(
        'INSERT INTO ratings (good_rating) VALUES ($1) RETURNING *',
        [good]
    );
    res.send({
     success:true,
     msg:"data saved"
    })
} catch (error) {
   res.send({
   success:false,
   msg:error.message
   });
}
});

and in the frontend you need to act bassed on that respond

const onClickGood = async (e) => {
    e.preventDefault();
   
        const body = { good };
        const response = await fetch('http://localhost:5555/good-rating', {
            method: 'POST',
            headers: { 'content-type': 'application/json' },
            body: JSON.stringify(body),
        }).then((res)=>res.json()).catch((err)=>console.log(err))
       if(response.success){
       //code here
       console.log(response)
      }else{
       console.log('Error')
       console.log(response)     
    }};

Leave a Reply

(*) Required, Your email will not be published