Home > other >  axios get request not fetch data on first click
axios get request not fetch data on first click

Time:10-03

I am trying to fetch data on button click. The problem is when I click on the button first-time data is not fetching. but when I click second time data is fetching properly.

here is my code

const learnMores = document.querySelectorAll('.learnMoreId');
const readmoreImg = document.querySelector('#readmoreImg');
const readMoreTitle = document.querySelector('#readMoreTitle');
const readMoresubTitle = document.querySelector('#readMoresubTitle');
const readmoreBody = document.querySelector('#readmoreBody');
learnMores.forEach((learnMore) => {
    learnMore.addEventListener('click', (e) => {
        e.preventDefault();
        if (e.currentTarget) {
            const { reamoreid } = e.target.dataset;
            axios.get(`/single-readmore/${reamoreid}`).then((response) => {
                readmoreImg.src = `/upload/readmore/${response.data.readMoreImage}`;
                readMoreTitle.innerText = response.data.title;
                readMoresubTitle.innerText = response.data.subTitle;
                readmoreBody.innerHTML = response.data.desciption;
            }).catch((error)=>{
                console.log(error);
            })
        }
    });
});

CodePudding user response:

try using async/await. Also why are you using e.preventDefault()?

learnMore.addEventListener('click', async (e) => {
        e.preventDefault();
        if (e.currentTarget) {
            const { readmoreid } = e.target.dataset;
            await axios.get(`/single-readmore/${readmoreid}`).then((response) => {
                readmoreImg.src = `/upload/readmore/${response.data.readMoreImage}`;
                readMoreTitle.innerText = response.data.title;
                readMoresubTitle.innerText = response.data.subTitle;
                readmoreBody.innerHTML = response.data.desciption;
            }).catch((error) => {
                console.log(error);
            })
        }
    });

CodePudding user response:

I don't see any erros in your code, but make sure "e.target.dataset" has values and api not returning any errors

  • Related