Asking
Asking

Reputation: 4172

Typescript in react JS

I am using react-select-async-paginate:

async function loadOptions(search, loadedOptions, { page }) {
  const response = await fetch(`/awesome-api-url/?search=${search}&page=${page}`);
  const responseJSON = await response.json();

  return {
    options: responseJSON.results,
    hasMore: responseJSON.has_more,
    additional: {
      page: page + 1,
    },
  };
}

<AsyncPaginate
  value={value}
  loadOptions={loadOptions}
  onChange={setValue}
  additional={{
    page: 1,
  }}
/>

How to apply the typescript for this code: (search, loadedOptions, { page }) taking into account that these are the types?

demo: https://codesandbox.io/s/react-select-async-paginate-forked-qiizl?file=/src/SelectAsyncPaginate.tsx

Upvotes: 3

Views: 652

Answers (1)

Mosh Feu
Mosh Feu

Reputation: 29239

As you can see loadOptions type is LoadOptions<OptionType, Additional>.

That's how you should type your loadOptions function

const loadOptions: LoadOptions<any, {page: number}> = ...

You should replace any with the actual option's type (you can figure it from the API response)

https://codesandbox.io/s/react-select-async-paginate-forked-00k7m?file=/src/SelectAsyncPaginate.tsx

Upvotes: 1

Related Questions