Source

hooks/use-multiple-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 multiple REST endpoints simultaneously.
  4. * For the equivalent hook for making requests to single URL, see {@link useFetch}
  5. *
  6. * @category Custom Hooks
  7. *
  8. * @example
  9. * // Makes a GET request to defined list of URLs
  10. * const URL_LIST= ['www.example.com','www.anotherexample.com']
  11. * useMultipleFetch(URL_LIST)
  12. *
  13. * @example
  14. * // Makes a POST request to lsit of URLs
  15. * useMultipleFetch(URL_LIST, 'POST')
  16. *
  17. * @param {string[]} urlList The list of REST endpoints 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 useMultipleFetch = (urlList, method = 'GET', body = null, startTime, endTime) => {
  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. Promise.all(urlList.map(url => fetch(url, requestOptions)))
  40. .then((responses) => {
  41. return Promise.all(responses.map((resp) => {
  42. if (resp.status >= 200 && resp.status <= 299 && resp.status !== 204){
  43. return resp.json();
  44. }
  45. else if(resp.status === 204){
  46. if(method === 'POST'){
  47. return [
  48. {time: new Date(startTime * 1000).toISOString(), value :null},
  49. {time: new Date(endTime * 1000).toISOString(), value:null}
  50. ]
  51. }
  52. return resp.json();
  53. }
  54. else{
  55. setstate({isLoading: false, isError: true, data:{}})
  56. throw new Error(resp.statusText);
  57. }
  58. }))
  59. })
  60. .then((resultsObj) => {
  61. console.log(resultsObj);
  62. setstate({isLoading: false, isError: false, data: resultsObj})
  63. })
  64. .catch((error) => {
  65. console.log("MULTIPLE FETCH ERROR> " + error);
  66. setstate({isLoading: false, isError: true, data: {}})
  67. });
  68. return () => {
  69. };
  70. }, [urlList, method, body, startTime, endTime])
  71. return {...state}
  72. }
  73. export default useMultipleFetch