Skip to content

Instantly share code, notes, and snippets.

@scottmatthewman
Last active February 25, 2019 17:25
Show Gist options
  • Save scottmatthewman/fb2c13a4f64d84f07affd6d50807bdb0 to your computer and use it in GitHub Desktop.
Save scottmatthewman/fb2c13a4f64d84f07affd6d50807bdb0 to your computer and use it in GitHub Desktop.
An example of compositing useState and useEffect hooks
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 };
};
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;
@scottmatthewman
Copy link
Author

Notes:

  • xFetch is our own Fetch implementation which injects Rails-specific CSRF tokens; other than that it uses the standard Fetch API

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment