Where can I make API call with hooks in react?

前端 未结 5 1341
有刺的猬
有刺的猬 2020-11-27 14:43

Basically we do API calls in componentDidMount() life cycle method in React class components like below

     componentDidMount(){
          //He         


        
5条回答
  •  情深已故
    2020-11-27 15:18

    You can use a library that provides the hooks for you like https://resthooks.io

    Then getting your data becomes as simple as:

    const article = useResource(ArticleResource.detailShape(), { id });
    

    Now you grabbed the article by id. All non-happy paths (loading, error states) are handled by Suspense and Error boundaries respectively.

    To get started follow this simple guide: https://resthooks.io/docs/getting-started/installation

    At only 7kb gzipped this will save you a lot of pain and in the long run lower your bundle size due to less repeated code.

提交回复
热议问题