zdd
zdd

Reputation: 8727

React Hook, how to avoid multiple call of api?

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.

  1. This only happened when user search on other pages(not the first page)
  2. When user search on page, I want the table to show search result from the first page.

the code as below, you can see the dependency of method useEffect:

  1. the search condition
  2. the 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

Answers (1)

LChuan
LChuan

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

Related Questions