score:5
Accepted answer
This is happening because whenever you scroll you are calling
window.onscroll = function (e) {
if (
window.innerHeight + document.documentElement.scrollTop ===
document.documentElement.offsetHeight
) {
setPage(page + 1);
}
};
And it's changing the page count and that changed page count leads to again run the
useEffect(() => {
const getPlaces = async () => {
try {
setIsLoading(true);
const url = `http://localhost:5000/api/places/user/${id}?page=${page}&size=3`;
const responseData = await fetch(url);
const data = await responseData.json();
console.log(data);
setLoadedPlaces((prev) => [...prev, ...data.places]);
setIsLoading(false);
} catch (error) {}
};
getPlaces();
}, [page]);
and in that function, you are doing setIsLoading(true)
so that it is again rendering this because of
{!isLoading && <-----
loadedPlaces.length > 0 &&
loadedPlaces.map((place, index) => (
<div key={index} className={"container"}>
<h1>{place.location.lat}</h1>
<h1>{place.location.lng}</h1>
<h1>{place.title}</h1>
<h1>{place.description}</h1>
<h1>{place.address}</h1>
<hr></hr>
</div>
))}
And that leads you to the top of the page
You can try this approach:
import React, { useEffect, useState } from "react";
import "./App.css";
function App() {
const [page, setPage] = useState(1);
const [loadedPlaces, setLoadedPlaces] = useState([]);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
const getPlaces = async () => {
try {
setIsLoading(true);
const url = `http://localhost:5000/api/places/user/${id}?page=${page}&size=3`;
const responseData = await fetch(url);
const data = await responseData.json();
console.log(data);
setLoadedPlaces((prev) => [...prev, ...data.places]);
setIsLoading(false);
} catch (error) {}
};
getPlaces();
}, [page]);
window.onscroll = function (e) {
if (
window.innerHeight + document.documentElement.scrollTop ===
document.documentElement.offsetHeight
) {
setPage(page + 1);
}
};
return (
<div className='App'>
<h1>Infinite Scroll</h1>
{
loadedPlaces.length > 0 &&
loadedPlaces.map((place, index) => (
<div key={index} className={"container"}>
<h1>{place.location.lat}</h1>
<h1>{place.location.lng}</h1>
<h1>{place.title}</h1>
<h1>{place.description}</h1>
<h1>{place.address}</h1>
<hr></hr>
</div>
))}
</div>
);
}
export default App;
score:0
You can add this.
function ScrollToBottom(){
const elementRef = useRef();
useEffect(() => elementRef.current.scrollIntoView());
return <div ref={elementRef} />;
};
And then:
return (
<div className='App'>
<h1>Infinite Scroll</h1>
{!isLoading &&
loadedPlaces.length > 0 &&
loadedPlaces.map((place, index) => (
<div key={index} className={"container"}>
<h1>{place.location.lat}</h1>
<h1>{place.location.lng}</h1>
<h1>{place.title}</h1>
<h1>{place.description}</h1>
<h1>{place.address}</h1>
<hr></hr>
</div>
))}
<ScrollToBottom />
</div>
);
Source: stackoverflow.com
Related Query
- stop/prevent scrolling to top on re render in React using Hooks (need to implement infinite scrolling)
- React.js: Stop render from scrolling to top of page
- How to prevent child component from re-rendering when using React hooks and memo?
- Prevent scrolling using CSS on React rendered components
- How to Add Smooth Scrolling Back To Top Button using react js?
- React context with hooks prevent re render
- Update React Hooks State During Render Using useMemo
- Using react hooks inside render prop function
- React Native - reduce render times to optimize performance while using React hooks
- How do I prevent the browser from scrolling to the top on render
- Prevent rerender using React hooks and onScroll or onWheel
- How to avoid unnecessary render in React using Hooks API
- How to stop browser back button using react js hooks and history api?
- How do I properly render React components using conditionals if I need to show custom prompt first?
- Make an API call on second render using React Hooks
- React - Prevent scrolling to top after changing query params
- How to dynamically and conditionally render select options inside of a map function using React Hooks
- How to render component conditionally when leaf value of global state changes using react hooks
- React Hooks - Prevent re-render when using prevState
- How to fix the Rendered more hooks than during the previous render using react hook
- With Firebase , using react hooks , objects are not valid as a React child , (If you meant) to render a collection of children, use an array instead
- Debouncing / throttling a callback in React using hooks without waiting for the user to stop typing to get the update
- How to render progress bar while using react hooks
- useState doesn't render results of axios call using async/await with React Hooks
- How to stop react component from going past the top of the page when scrolling
- How to prevent an infinite loop in react using Hooks
- React Hooks like ComponentDidMount, not using render counts
- Material UI Nested lists using recursive render is not working with react hooks
- need to implement Undo function using react hooks
- React component not scrolling to top on re render
More Query from same tag
- button to act as checkbox and change styles?
- Data fetching with React hooks cleanup the async callback
- Nginx Subfolder admin react app under main react app
- Using i18next for a react production build causes the translation to display only strings
- Warning: Expected server HTML to contain a matching <div> in <div>
- Problem twice click on submit handler in React JS
- React JS creating interface for an array being passed to map function array.map(item:???)
- Confirmation button, triggers all confirmation boxes to open
- How do I get React to work with Babel and Gulp?
- Storybook: Objects are not valid as a React child when not using backticks after .attrs
- Insert data using multiple components in reactjs
- Getting InvalidValueError while passing state by useContext
- What exactly is makeStyles in material-ui?
- Deleting a list item when it's clicked in React
- ReactJs input first value getting empty
- Clarification on useEffect dependency array
- Make Card (or Paper) NOT take up full width Material UI
- Getting error that my function is not defined
- Using Validation on a FormSection with Redux Forms
- dynamic File inside folders not reading with React and preval.macro
- Radio button not working correctly when rendered using array Data
- How to use react as a component library rather than application
- Testcafe wont recognise React
- Mocking a function returned by a react hook
- How to write validations for email and password using react hooks
- ionic react, scroll to specific list item
- ReactJs Accordion Automatic Close Mechanism
- React scroll to ref with multiple scrollbars
- How can i simplify my current React code?
- Is it Possible to use Enzyme testing with Next js (SSR)?