- Lots of hooks to perform common tasks can make our components big and hard to read
- Imagine if every page required setting up state, fetching data from an API, updating the data etc
- What if we could do it all in one neat package
function useRestfulApi (resourceName, resourceId, initialState) {
const [resource, setResource] = React.useState(initialState);
const url = `https://example.com/${resourceName}/${resourceId}`
React.useEffect(function () {
const controller = new AbortController();
fetch(url, {
method: 'GET'
}).then(function (response) {
return response.json();
}).then(setResource);
return controller.abort();
}, [resourceId]);
function updateResource (resourceData) {
fetch(`http://localhost:3000/users/${props.userId}`, {
method: 'PUT'
body: JSON.stringify(resourceData)
}).then(function (response) {
return response.json();
}).then(setResource);
}
return {
resource: resource,
updateResource: updateResource
}
}
function UserComponent (props) {
const [resource, updateResource] = useApi("user", props.userId, {});
return <UserForm onChange={updateResource} user={resource} />
}