Source

hooks/use-fetch.js

  1. import { useEffect, useState } from 'react'
  2. /**
  3. * This is a custom React Hook that is used to fetch and post data to a REST endpoint.
  4. * For the equivalent hook for making requests to multiple URL, see {@link useMultipleFetch}.
  5. *
  6. * @category Custom Hooks
  7. *
  8. * @example
  9. * // Makes a GET request to defined URL
  10. * const URL= 'www.example.com'
  11. * useFetch(URL)
  12. *
  13. * @example
  14. * // Makes a POST request to URL
  15. * useFetch(URL, 'POST')
  16. *
  17. * @param {string} url The REST endpoint data should be fetched from or posted to.
  18. * @param {string} [method = GET] The HTTP method to be used in the request. Defaults to a GET request.
  19. * @param {Object} [body = null] The body of the HTTP request.
  20. * @param {number} [startTime] The start time for a request given in UTC epoch time. It is also used in refreshing requests at intervals.
  21. * @param {number} [endTime] The end time for a request given in UTC epoch time.
  22. * @param {string} [type] The type of the sensor making the request.
  23. * @returns {Object} returns the data object along with whether there is an error or not.
  24. */
  25. const useFetch = (url, method = 'GET', body = null, startTime, endTime, type) => {
  26. const [state, setstate] = useState({isLoading: true, isError: false, data: {}})
  27. useEffect(() => {
  28. const myHeaders = new Headers();
  29. myHeaders.append("x-api-key", "F7BVJtZSo38Hw22aI3QWkLDJ9M0pMc70");
  30. myHeaders.append("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJGbU1ia004UXhyaXozaDl5MzZad0JOaUVZSFZnR0lsTiJ9.sg650g2TmNP9EnMbgA7l9MzciXBkxBTTr6hYHXOz7QI");
  31. myHeaders.append("X-Host-Override", "wot-device-api");
  32. myHeaders.append("Content-type", "application/json; charset=UTF-8");
  33. const requestOptions = {
  34. method: method,
  35. headers: myHeaders,
  36. body: body,
  37. redirect: 'follow'
  38. };
  39. fetch(url, requestOptions)
  40. .then((resp) => {
  41. if (resp.status >= 200 && resp.status <= 299 && resp.status !== 204){
  42. return resp.json();
  43. }
  44. else if(resp.status === 204){
  45. if(method === 'POST'){
  46. return [
  47. {time: new Date(startTime * 1000).toISOString(), value :null},
  48. {time: new Date(endTime * 1000).toISOString(), value:null}
  49. ]
  50. }
  51. }
  52. else{
  53. setstate({isLoading: false, isError: true, data:{}})
  54. throw new Error(resp.statusText);
  55. }
  56. })
  57. .then((resultsObj) => {
  58. console.log(resultsObj);
  59. if(method === 'POST'){
  60. if (!resultsObj[0].hasOwnProperty('value')){
  61. if(type === 'onOff' || type === 'openClose' || type === 'motionDetected'){
  62. let firstValue = !resultsObj[0][type]
  63. let lastValue = resultsObj[resultsObj.length - 1][type]
  64. let firstItem = {time: new Date(startTime * 1000).toISOString(), value :firstValue}
  65. let lastItem = {time: new Date(endTime * 1000).toISOString(), value:lastValue}
  66. resultsObj = [firstItem, ...resultsObj, lastItem];
  67. }
  68. }
  69. console.log('resultsObj: ' + resultsObj)
  70. }
  71. setstate({isLoading: false, isError: false, data: resultsObj})
  72. })
  73. .catch((error) => {
  74. console.log("ERROR> " + error);
  75. setstate({isLoading: false, isError: true, data: {}})
  76. });
  77. return () => {
  78. };
  79. }, [url, method, body, startTime, endTime, type])
  80. return {...state}
  81. }
  82. export default useFetch