I'd like to implement pagination by having a button to load more data from youtube api. To go to next/ previous pages, youtube api require pagetoken. As a beginner, while I know how to fetch the initial data, I don't know how to load more data using pagetoken in a useEffect hook. I thought if I create onClick event on the button and pass the initial fetch function in it, that would solve the problem but it doesn't. So here's my code :
function VideoList() {
const [videoList, setvideoList] = useState([]);
const [pageToken, setPageToken] = useState("");
const baseURL = `https://youtube.googleapis.com/youtube/v3/activities?part=snippet`;
const maxResults = `maxResults=20`;
const channelId = `channelId=${process.env.REACT_APP_CHANNEL_ID}`;
const apiKey = `key=${process.env.REACT_APP_API_YOUTUBE}`;
const request = `${baseURL}&${channelId}&${apiKey}&${maxResults}${pageToken}`;
const fetchVideos = async () => {
try {
const response = await axios.get(request);
const responseResult = response.data;
setvideoList(responseResult.items);
setPageToken(`&pageToken=${responseResult.nextPageToken}`);
} catch (error) {
console.log(error.message);
}
};
useEffect(() => {
fetchVideos();
}, []);
if (videoList.length === 0) {
return null;
}
return (
<>
<NavBar />
<div className="m-8">
<VideoCard videos={videoList} />
<button
className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-full shadow"
onClick={fetchVideos()}
>
More Videos
</button>
</div>
<SiteFooter />
</>
);
}
export default VideoList;
However, when I click the button, the following error happened
Warning: Expected
onClick
listener to be a function, instead got a value ofobject
type.
Any idea how to correctly implement this? Help would be very much appreciated and thank you in advance!
I think the only thing you need is merge the old state with the new state:
setvideoList((oldData) => [...oldData, ...responseResult.items]);