Reputation: 33
I am trying to create an infinite scroll by setting lazyload but I can't set the states each times in postData functions.
I can see the arr array works properly but it doesn't be setted in setCards(arr). I can't see the update in Devtolls Component Tools
If you have any idea I appriciated..
const postData = async (searchInputValue,payload) => {
const response = await fetch("https://smarty.kerzz.com:4004/api/mock/getFeed", {
body: JSON.stringify(payload),
headers: {
Accept: "application/json",
Apikey: "bW9jay04ODc3NTU2NjExMjEyNGZmZmZmZmJ2",
"Content-Type": "application/json"
},
method: "POST"
})
const data = await response.json()
let arr =[...cards]
console.log(cards)
data.response.forEach((item, idx)=>{
arr.push(item)
})
console.log(arr) //[]
setCards(arr)
let a = counter + 1
let new_payload = payload;
new_payload.skip += 10*a
setPayload(new_payload)
setCounter(a)
}
useEffect(()=>{
// İlk yükleme sırasında lokasyon verisini alıp fonksiyonu çağırıyoruz. Aldığımız lokasyon
verisine göre işlemlere devam edeceğiz.
findLocation();
window.addEventListener('scroll' , ()=>{
let screen_height = window.innerHeight;
let scrollTop = document.documentElement.scrollTop;
var body = document.body,
html = document.documentElement;
var body_heigth = Math.max( body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight );
if(scrollTop + 1 > body_heigth - screen_height && isloading === false && checked === false){
setIsloading(true)
postData(searchInputValue , payload)
}
})
},[])
Upvotes: 0
Views: 47
Reputation: 1861
If the new state is computed using the previous state, you can pass a function to setState. The function will receive the previous value, and return an updated value.
https://reactjs.org/docs/hooks-reference.html#functional-updates
Example:
setCounter((counter)=>(counter+1))
setCards((cards)=>(cards.concat(data.response)))
Do the same for setPayload
.
Upvotes: 2