Skip to content

Instantly share code, notes, and snippets.

@viniciusdacal
Created April 11, 2020 19:10
Show Gist options
  • Save viniciusdacal/e20053fd2381e7403b0f5309446052bf to your computer and use it in GitHub Desktop.
Save viniciusdacal/e20053fd2381e7403b0f5309446052bf to your computer and use it in GitHub Desktop.
import { useState } from 'react';
import axios from 'axios';
const api = axios.create({
baseURL: '/api'
});
const initialState = { pending: true, error: null, data: null };
export default function useLazyRest(options = {}) {
const [state, setState] = useState(initialState);
async function call(newOptions) {
setState({ pending: true, error: null, data: null });
try {
const response = await api.request({
...options,
...newOptions
});
setState({ pending: false, error: null, data: response.data });
} catch(err) {
setState({ pending: false, error: err, data: null });
}
}
return [call, state];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment