I'm working on a project using react (next.js) and I can get data from Api perfectly, but for some reasons (performance and ...) the Api doesn't return the whole data and I should get one slice of the data time to time until the Api method returns empty array([]). my Api function is this:
getBlogList(count,skip)
count is the count of returned blogs and skip is count of skipped blogs.
I have show more button to show more blogs when the user click it.
The show more buttons works good. But I want the page to be shown after refresh just like it did at the first render. But when I refresh the page I see it messy. for example some times I didn't see any blog title or I see only the last one! when I logged the skip state in showMoreBlogs function, it was not 0. Although I set it to zero in the useEffect() and it was expected to be 0 after refresh!
This is my code :
const count=3
const [blogs,setBlogs]:any[]=useState([])
var [skip,setSkip]=useState(0);
const getBlogs=()=>{
await getBlogList(count,skip).then(async(response:any)=>{
console.log(response)
setBlogs(response.data)
setSkip(skip+count)
}).catch((er)=>{console.log(er); return []})
}
useEffect(()=>{
setSkip(0)
getBlogs();
},[])
//wehn you click on the show more button
const showMoreBlogs=()=>{
console.log(skip)
await getBlogList(count,skip).then(async(response:any)=>{
console.log(response.data)
if(response.data.length>0){
setBlogs([...blogs,...response.data])
console.log(response.data)
setSkip(skip+count)
console.log(skip+count)
}
}
}
return(<>
{blogs.map((el)=>{
return <span>{el.title}</span>
})}
<button className={` hover-up-5 top-0 relative inline-block py-4 duration-500 px-8 text-xs text-white font-semibold leading-none bg-color-400 hover:bg-color-500 rounded`}
onClick={(e)=>{e.preventDefault();showMoreBlogs();}}
>Show more</button>
</>)
It turned out that the skip state saves the previous value after the refresh! What should I do to refresh skip state after refreshing the page?