Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { useState, useEffect } from 'react'
- import { PersonsApi } from '../Api/PersonsApi'
- const ApiNameMapper = {
- PersonsApi,
- }
- const useApi = (apiName, apiMethod, initialData = null) => {
- const [response, setResponse] = useState(null)
- const [isLoading, setIsLoading] = useState(false)
- const [isError, setIsError] = useState(false)
- const [data, setData] = useState(initialData)
- const api = ApiNameMapper[apiName]
- useEffect(() => {
- if (data === null) return
- const fetchData = async () => {
- setIsError(false)
- setIsLoading(true)
- try {
- const result = await api[apiMethod](data)
- setResponse(result)
- } catch (error) {
- setIsError(true)
- }
- setIsLoading(false)
- }
- fetchData()
- }, [data])
- const changeData = (property, value) => {
- setData({
- ...data,
- [property]: value,
- })
- }
- return { response, isLoading, isError, data, changeData }
- }
- export default useApi
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement