Reputation: 8727
I use React hook and AntD table, the table has several pages to show the data from a backend server, now the problem is when users search on pages, the same api called two times, I know why this happened, but I don't know hot to avoid it.
the code as below, you can see the dependency of method useEffect
:
pageNum
and pageSize
When user input the search condition, and click search
button, the api was fired(since searchCondition
was changed). and then i update pageNum
to 1
, the api fired again!(since pageNum
was changed), how to make the api only called one time? thanks.
useEffect(() => {
getUsers(pageNum, pageSize, searchCondition)
}, [searchCondition, pageNum, pageSize])
and here is the handler for search
button.
const listUser = (params: any) => {
setSearchCondition(params)
setPageNum(1)
}
Upvotes: 1
Views: 251
Reputation: 363
To avoid this, you may combine both of the actions into an action by using useReducer
.
Replace useState
by useReducer
const [state, dispatch] = useReducer(
(state, action) => ({ ...state, ...action }),
{
searchCondition: initialState,
pageNum: initialState
}
);
Combine your action
const listUser = (params: any) => {
dispatch({
searchCondition: params,
pageNum: 1
});
}
Call API
useEffect(() => {
getUsers(state.pageNum, pageSize, state.searchCondition)
}, [state.searchCondition, state.pageNum, pageSize])
Upvotes: 1