Promice is rewriting value of hook, i tried to get more values to my posts, but promise keep replacing value of hook with value of data
const loadNewProducts = async() =>{
while(posts.length<15){
await fetch (`http{loadLimit[0]}&limit=${loadLimit[1]}&sort=title%3Aasc`)
.then((res) => res.json())
.then((data) => {
data.data.map((data: { id: any; }) => {if (posts.includes((post: { id: any; }) => post.id!=data.id)||posts.length==0) {setPosts(posts => [...posts, data])}});
setPosts(posts => posts.slice(-data.data.length));console.log(posts);
})
.catch((err) => {
console.log(err.message);
});
loadLimit = [loadLimit[0],loadLimit[1]+1];if(loadLimit[1]==13){loadLimit = [loadLimit[0]+1,1]}}}
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(() => {{loadNewProducts();console.log(posts);loadNewProducts();console.log(posts)}}, [])
I trie a lot of ways to solve this, but nothing helped
2
Answers
try using useRef like below –
let me know if it worked. change
YourComponent
to whatever your component is