Need to update the useEffect call when I update the state. can anyone correct the code? Currently is working like this screenshot the updated data is rendering after pre-render data. what is needed is when I click on any filter every it renders new data. Check screenshot
Here is my code :
const PAGE_NUMBER =1;
export const SimpleInfiniteList = () => {
const [img, setImg] = useState('')
const [page, setPage] = useState(PAGE_NUMBER)
const iddata = img.slice(-1)
const [filter, setFilter] = useState('top')
const [, forceUpdate] = useReducer(x => x + 1, 0);
useEffect(() => {
const filt = () => {
if(filter > 0){
filt()
}
}
}, [])
useEffect( () => {
forceUpdate()
fetch(`https://www.reddit.com/r/ProgrammerHumor/${filter}.json?after=${ iddata.length > 0 ? iddata.map(id => `t3_${id.data.id}`): ''}&page=${page}&limit=2`)
.then(response => response.json())
.then(data => setImg([...img, ...data.data.children],
)
)
}, [filter,page])
console.log(img)
const scrollToEnd = () => {
setPage(page + 1)
}
window.onscroll = function () {
const bottom = Math.ceil(window.innerHeight + window.scrollY) >= document.documentElement.scrollHeight
if (bottom,
Math.ceil(window.innerHeight + window.scrollY) >= document.documentElement.scrollHeight
) {
scrollToEnd()
console.log('loading....')
}
}
}