I want to make an API call that's based on the current state, but can't make the setState function work as an asynchronous function.
handlePage = (direction: number) => {
this.setState( async (state) => {
const tickets: Ticket[] = await api.getTickets(`?page=${state.pageNum + direction}`)
const pageNum: number = state.pageNum + direction;
return { pageNum, tickets };
});
}
Gets me the error:
Argument of type '(state: Readonly) => Promise<{ pageNum: number; tickets: Ticket[]; }>' is not assignable to parameter of type 'AppState | ((prevState: Readonly, props: Readonly<{}>) => AppState | Pick<AppState, "tickets" | "search" | "theme" | "pageNum"> | null) | Pick<...> | null'. Type '(state: Readonly) => Promise<{ pageNum: number; tickets: Ticket[]; }>' is not assignable to type '(prevState: Readonly, props: Readonly<{}>) => AppState | Pick<AppState, "tickets" | "search" | "theme" | "pageNum"> | null'. Type 'Promise<{ pageNum: number; tickets: Ticket[]; }>' is not assignable to type 'AppState | Pick<AppState, "tickets" | "search" | "theme" | "pageNum"> | null'. Type 'Promise<{ pageNum: number; tickets: Ticket[]; }>' is missing the following properties from type 'Pick<AppState, "tickets" | "search" | "theme" | "pageNum">': search, theme, pageNumts(2345)
It works if I fetch the data outside the setState method, but I'm afraid to make an API call to an outdated page number:
handlePage = async (direction: number) => {
const tickets: Ticket[] = await api.getTickets(`?page=${this.state.pageNum + direction}`)
this.setState( (state) => {
const pageNum: number = state.pageNum + direction;
return { pageNum, tickets };
});
}
asyncit then implicitly returns a Promise and that appears to not be compatible with your declared state type declaration. What do you mean by "outdated page number"?this.state.pageNumwill be the value from the current render cycle whenhandlePageis invoked. - Drew Reesethis.state.pageNumisn't being used in rendering any part of the UI but being used only for API call, you can store it as ref usinguseRefhook. - Ajeet Shahoutdated page number??- Debarshi Bhattacharjeeoutdated page numberI mean that if I will not set the state using the previous state, multiple quick clicks might failure to update the state as explained in react documentation - Oz Heymann