Last active
          February 25, 2019 17:25 
        
      - 
      
 - 
        
Save scottmatthewman/fb2c13a4f64d84f07affd6d50807bdb0 to your computer and use it in GitHub Desktop.  
    An example of compositing useState and useEffect hooks
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | import { useState, useEffect } from 'react'; | |
| import xFetch from '../utils/x_fetch'; | |
| export const useFetch = (url) => { | |
| const [error, setError] = useState(null); | |
| const [isLoading, setIsLoading] = useState(true); | |
| const [data, setData] = useState([]); | |
| useEffect(() => { | |
| setIsLoading(true); | |
| xFetch(url) | |
| .then(response => { | |
| if (response.ok) { | |
| return response.json(); | |
| } else { | |
| throw new Error(response.statusText); | |
| } | |
| }) | |
| .then(json => setData(json)) | |
| .catch(error => setError(error)) | |
| .then(() => setIsLoading(false)); | |
| }, [url]); | |
| return { data, isLoading, error }; | |
| }; | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | import React from 'react'; | |
| import { useFetch } from './hooks'; | |
| import RecommendationsList from './RecommendationsList'; | |
| import Loader from 'components/loader'; | |
| const RecommendationsListContainer = () => { | |
| const { data: recommendations, isLoading } = useFetch('/recommendations.json'); | |
| return ( | |
| <React.Fragment> | |
| {isLoading ? | |
| <Loader /> | |
| : | |
| <RecommendationsList recommendations={recommendations} /> | |
| } | |
| </React.Fragment> | |
| ); | |
| }; | |
| export default RecommendationsListContainer; | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Notes:
xFetchis our own Fetch implementation which injects Rails-specific CSRF tokens; other than that it uses the standardFetchAPI