Created
April 11, 2020 19:10
-
-
Save viniciusdacal/e20053fd2381e7403b0f5309446052bf to your computer and use it in GitHub Desktop.
This file contains 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 } 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