Commit d2ad01e1 authored by Ken's avatar Ken

enhance avoid increasing pages when no data

parent 49667e35
......@@ -40,7 +40,7 @@
&__desc {
line-height: 22px;
font-size: 14px;
font-size: 18px;
color: $neutral-900;
display: block;
}
......
......@@ -2,8 +2,9 @@ import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import newsApi from "api/newsApi";
import { INewspaper, IPagination } from "pages/interface";
const initialState: { newsData: INewspaper[] } = {
const initialState: { newsData: INewspaper[]; currentPage: number } = {
newsData: [],
currentPage: 0,
};
export const getNews = createAsyncThunk(
......@@ -19,17 +20,24 @@ const home = createSlice({
initialState,
reducers: {
handleResetNews: (state) => {
state.newsData = [];
return initialState;
},
loadPages: (state) => {
state.currentPage++;
},
},
extraReducers: (builder) => {
builder.addCase(getNews.fulfilled, (state, action: PayloadAction<any>) => {
const { collection } = action.payload.data;
if (collection.length > 0) {
state.currentPage++;
state.newsData = [...state.newsData, ...collection];
}
});
},
});
const { reducer, actions } = home;
export const { handleResetNews } = actions;
export const { handleResetNews, loadPages } = actions;
export default reducer;
......@@ -10,7 +10,7 @@ import { CircularProgress } from "@mui/material";
const HomePage = () => {
const dispatch = useAppDispatch();
const { newsData } = useAppSelector(homeSelector);
const { newsData, currentPage } = useAppSelector(homeSelector);
const { ref, inView } = useInView({
threshold: 0.7,
initialInView: false,
......@@ -21,6 +21,7 @@ const HomePage = () => {
useEffect(() => {
try {
if (page > currentPage) {
setIsLocalLoading(true);
setTimeout(() => {
const newsParams: IPagination = {
......@@ -30,12 +31,17 @@ const HomePage = () => {
PageSize: 10,
};
const fetchData = async () => {
await dispatch(getNews(newsParams));
const res: any = await dispatch(getNews(newsParams)).unwrap();
if (res.data.collection.length === 0) {
setPage((page) => page - 1);
}
};
fetchData();
setIsLocalLoading(false);
}, 1000);
}
} catch (err) {
console.error("ERROR: ", err);
setIsLocalLoading(false);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment