简体   繁体   中英

Defining type for an InfiniteScroll react component with typescript

I'm trying to create a InfiniteScroll component to use it in this way:

import { getData } from 'api';
import { InfiniteScroll } from 'components';

export const App = () => (
  <InfiniteScroll fetcher={page => getData({page})}>
    {({items}) => items.map(item => <p key={item.id}>{item.name}</p>)}
  </InfiniteScroll>
);

and getData is a function that get page as its parameter and returns a Promise like this:

type Data = {
  id: number;
  name: string;
};

function getData(args: { page: number }): Promise<Data[]> {
  // ...
}

Now my question is how can I define type for my InfiniteScroll component to set type for its render prop function automatically?

Actually I want items in the render props retrieve its type from Data[] that is return value of the Promise used in fetcher prop

I added this codesandbox for working on it:
https://codesandbox.io/s/vigorous-resonance-lj09h?file=/src/InfiniteScroll.tsx

If we could see the InfiniteScroll component code, we could probably help you better but essentially, you have to do something like below.

interface Props<T> {
  fetcher: (page: number) => Promise<T[]>;
  children: (data: T[]) =>  JSX.Element;
}

export const InfiniteScroll = <T extends unknown>({
  fetcher,
  children
}: Props<T>) => {
  const [page, setPage] = useState(1);
  const [data, setData] = useState<T[] | null>(null);

  useEffect(() => {
    fetcher(page).then((res) => {
      setData(res);
    });
  }, [page]);

 if (!data) return (
    <p> loading... </p>
  )
  return (children(data))
};

App.tsx:

export default function App() {
  return (
    <>
      <InfiniteScroll fetcher={(page: number) => getData(page)}>
        {(items) => (<>
           {(items.map((item, 
            index) => <p key={index}> {item.name} </p> ))} 
         </>)}
      </InfiniteScroll>
    </>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM