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);
})
}
});
});
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);
})
}
});
I don't see any erros in your code, but make sure "e.target.dataset" has values and api not returning any errors
Related
I need help retrieving firebase data in React Native, using expo.
This code works fine when I refresh the app, but when it first starts, it throws an error:
Error: Error: Client is offline.
Maybe I need to do it async and await, I have tried some ways, but no success.
componentDidMount = async () => {
var radioFireData = null;
const { names } = this.props;
const dbRef = ref(db, "records/");
get(child(dbRef, "flap/"))
.then((snapshot) => {
if (snapshot.exists()) {
radioFireData = snapshot.val();
this.setState({ checked: radioFireData[names] });
} else {
console.log("No data available");
}
})
.catch((error) => {
console.log(error);
});
};
Here it is... Maybe I can help someone.
componentDidMount(){
const { names } = this.props;
const reference = ref(db, "records/" + "/flap/");
onValue(
reference,
(snapshot) => {
const data = snapshot.val();
this.setState({ checked: data[names] });
},
{
onlyOnce: true,
}
);
};
I switched all my loaders from jQuery to Fetch and now none of the sliders are working but the slides themselves are showing up correctly in the DOM. I just can't seem to target them with JS.
https://www.harpercollege.edu/dev/whoward-dev-area/dev-index.php
fetch('/_resources/php/dev-home-interrupter-loader.php')
.then(function(response) {
return response.text();
})
.then(function(body) {
document.querySelector('#home-interrupter').innerHTML = body;
});
const interrupterslidesContainer = document.getElementById("interrupter-slides-container");
const interrupterslide = document.querySelector(".interrupter-slide");
const previnterrupter = document.getElementById("interrupter-slide-arrow-prev");
const nextinterrupter = document.getElementById("interrupter-slide-arrow-next");
nextinterrupter.addEventListener("click", () => {
const interrupterslideWidth = interrupterslide.clientWidth;
interrupterslidesContainer.scrollLeft += interrupterslideWidth;
});
previnterrupter.addEventListener("click", () => {
const interrupterslideWidth = interrupterslide.clientWidth;
interrupterslidesContainer.scrollLeft -= interrupterslideWidth;
});
Your code runs before the fetch even starts
fetch('/_resources/php/dev-home-interrupter-loader.php')
.then(function(response) {
return response.text();
})
.then(function(body) {
document.querySelector('#home-interrupter').innerHTML = body;
})
.then(() => {
const interrupterslidesContainer = document.getElementById("interrupter-slides-container");
const interrupterslide = document.querySelector(".interrupter-slide");
const previnterrupter = document.getElementById("interrupter-slide-arrow-prev");
const nextinterrupter = document.getElementById("interrupter-slide-arrow-next");
nextinterrupter.addEventListener("click", () => {
const interrupterslideWidth = interrupterslide.clientWidth;
interrupterslidesContainer.scrollLeft += interrupterslideWidth;
});
previnterrupter.addEventListener("click", () => {
const interrupterslideWidth = interrupterslide.clientWidth;
interrupterslidesContainer.scrollLeft -= interrupterslideWidth;
});
})
Right now I'm working on full stack application that uses JS on the front and back end. This app lets a user generate their own set of flash cards. Whenever the user clicks "View Cards" data will then be fetched and will display the question and answer on each side of the card. It's supposed to display one card at a time and allows the user to scroll through other cards using either the "Previous" or "Next" buttons. I'm able to successfully fetch data convert it to JSON and can get at least one item from the data base display properly. The problem is whenever I try to scroll through the cards. I'm only able to scroll through some of the cards before the browser returns an error. I've even noticed that some of the cards won't render both sides properly. How could I address these issues?
const flashCard = document.querySelector(".flashcard");
const flipBtn = document.querySelector(".flip-btn");
const prevBtn = document.querySelector(".prev-btn");
const nextBtn = document.querySelector(".next-btn");
let frontOfCard = document.querySelector(".front-content");
let backOfCard = document.querySelector(".back-content");
const displayCards = () => {
getCardInfo()
flipBtn.innerHTML = "Flip"
flipBtn.removeEventListener("click", displayCards)
}
flipBtn.addEventListener("click", displayCards)
const flash = () => {
if (flashCard.style.transform != "rotateX(180deg)") {
flashCard.style.transform = "rotateX(180deg)"
} else {
flashCard.style.transform = "none"
}
}
const getCardInfo = async () => {
const itemBody = {
method: "PUT",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
}
const data = await fetch(window.location.href, itemBody)
const jsonData = await data.json()
console.log(jsonData)
let idx = 0;
frontOfCard.innerHTML = jsonData[idx].Answer
backOfCard.innerHTML = jsonData[idx].Question
flashCard.style.display = "block";
flipBtn.addEventListener("click", flash);
scrollThroughCards(idx, jsonData);
}
function scrollThroughCards(idx, data) {
prevBtn.addEventListener("click", (e) => {
flashCard.style.display = "none"
setTimeout(() => {
frontOfCard.innerHTML = data[idx--].Answer
backOfCard.innerHTML = data[idx--].Question
flashCard.style.display = "block"
}, 1000)
e.preventDefault()
})
nextBtn.addEventListener("click", (e) => {
flashCard.style.display = "none"
setTimeout(() => {
frontOfCard.innerHTML = data[idx++].Answer
backOfCard.innerHTML = data[idx++].Question
flashCard.style.display = "block"
}, 1000)
e.preventDefault()
})
}
app.get("/card/:id", checkAuthenticated, async (req,res) => {
const { id } = req.params
const data = await Card.findAll({ where: { NoteId: id } });
res.render("cards-page", {
noteid: id,
Cards: data
})
});
app.put("/card/:id", checkAuthenticated, async (req,res) => {
const { id } = req.params
const data = await Card.findAll({ where: { NoteId: id } });
res.json(data)
})
app.post("/card/:id", checkAuthenticated, async (req, res) => {
const { Question, Answer, NoteId } = req.body;
const newCard = await Card.create({
Question,
Answer,
NoteId
});
res.redirect(`/card/${NoteId}`)
});
In the scrollThroughCards function, boundary checks were not performed and the increment and decrement operators were misused.
function scrollThroughCards(idx, data) {
prevBtn.addEventListener("click", (e) => {
// there's no more card on the left of index 0
// so exit the function early
if (idx <= 0) return;
flashCard.style.display = "none"
setTimeout(() => {
idx--; // decrease the index first
// then use the modified index
frontOfCard.innerHTML = data[idx].Answer
backOfCard.innerHTML = data[idx].Question
flashCard.style.display = "block"
}, 1000)
e.preventDefault()
})
nextBtn.addEventListener("click", (e) => {
// there's no more cards beyond the end of the list
// so exit the function early
if (idx >= data.length - 1) return;
flashCard.style.display = "none"
setTimeout(() => {
idx++; // increase the index first
// then use the modified index next
frontOfCard.innerHTML = data[idx].Answer
backOfCard.innerHTML = data[idx].Question
flashCard.style.display = "block"
}, 1000)
e.preventDefault()
})
}
I tried to download the image which is in firebase storage which link is store in database. When I tried to download the image, it takes more time to execute while for loop is completed.
Is there any process that somehow I download in time which doesn't make the function really slow? I already solve this issue using setTimeout but I hope there may be a better solution than mine. Help me! thank you!
export const shampooHandler = () => {
return (dispatch) => {
dispatch(shampooStart());
const data = [];
const imgList = [];
fire
.database()
.ref()
.child("Shampoo")
.once("value")
.then((response) => {
for (let i = 0; i < response.val().length; i++) {
fire.storage().refFromURL(response.val()[i].img).getDownloadURL().then((image) => {
imgList.push(image);
})
.catch((error) => {
dispatch(shampooError(error));
});
setTimeout(() => {
name = response.val()[i].name;
description = response.val()[i].description;
value = response.val()[i].value;
img = imgList[i];
data.push({ name, description, value, img });
if (i === (response.val().length - 1)) {
dispatch(shampooSuccess(data));
}
}, 3000);
}
})
.catch((error) => {
dispatch(shampooError(error));
});
};
};
I spend a day finding a right solution for it. It may help someone to find solution in future. Thanks guys for giving a thought and specially DougStevensen to tiggering me an idea
export const shampooHandler = () => {
return (dispatch) => {
dispatch(shampooStart());
const data = [];
const imglist = [];
fire.database().ref().child("Shampoo").once("value").then((response) => {
response.val().forEach(element => {
const promise = imageUrlHandler(element.img).then(url => {
return url;
}).catch(error =>{
dispatch(shampooError(error));
})
imglist.push(promise);
//all the promise call to download the images
Promise.all(imglist).then(items =>{
const dataCollection = {
name: element.name,
description: element.description,
value: element.value,
img: items[items.length - 1]
}
data.push(dataCollection);
if(data.length === response.val().length){
dispatch(shampooSuccess(data));
}
}).catch(err =>dispatch(shampooError(err)));
})
}).catch(error => {
dispatch(shampooError(error));
})
}
}
export const imageUrlHandler = (databaseUrl) => {
return new Promise((resolve,reject)=> {
fire.storage().refFromURL(databaseUrl).getDownloadURL().then((url) => {
resolve(url);
})
.catch((error) => {
reject(error)
});
})
}
I have the following code for saving data to the table.
let Parse = require('parse').Parse;
export const gameInsert = async (data) => {
try {
const game = Parse.Object.extend('Table');
const query = new game();
data.forEach((item) => {
query.set('name', 'NewName');
query.save();
}, this);
} catch (e) {
console.log(e);
}
};
But it gives me no warning or error and the record is not saving. What am i missing ?
Have you try, query.save(null); ?