Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. import { useState, useEffect } from 'react'
  2.  
  3. import { PersonsApi } from '../Api/PersonsApi'
  4.  
  5. const ApiNameMapper = {
  6. PersonsApi,
  7. }
  8.  
  9. const useApi = (apiName, apiMethod, initialData = null) => {
  10. const [response, setResponse] = useState(null)
  11. const [isLoading, setIsLoading] = useState(false)
  12. const [isError, setIsError] = useState(false)
  13. const [data, setData] = useState(initialData)
  14. const api = ApiNameMapper[apiName]
  15.  
  16. useEffect(() => {
  17. if (data === null) return
  18.  
  19. const fetchData = async () => {
  20. setIsError(false)
  21. setIsLoading(true)
  22.  
  23. try {
  24. const result = await api[apiMethod](data)
  25.  
  26. setResponse(result)
  27. } catch (error) {
  28. setIsError(true)
  29. }
  30.  
  31. setIsLoading(false)
  32. }
  33.  
  34. fetchData()
  35. }, [data])
  36.  
  37. const changeData = (property, value) => {
  38. setData({
  39. ...data,
  40. [property]: value,
  41. })
  42. }
  43.  
  44. return { response, isLoading, isError, data, changeData }
  45. }
  46.  
  47. export default useApi
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement