-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils_hooks_useFetchAllData.jsx.html
136 lines (110 loc) · 5.62 KB
/
utils_hooks_useFetchAllData.jsx.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JSDoc: Source: utils/hooks/useFetchAllData.jsx</title>
<script src="scripts/prettify/prettify.js"> </script>
<script src="scripts/prettify/lang-css.js"> </script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>
<body>
<div id="main">
<h1 class="page-title">Source: utils/hooks/useFetchAllData.jsx</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>import { useEffect, useState } from "react";
import mockApi from "../../__mocks__/mockApi";
/**
* Custom React hook that fetches user's data from many endpoints
* @function useFetchAllData
* @param {number} id - the id of the user's data to fetch
* @returns {Object} an object with the `data`, `error` and `loading` states of the hook
*/
export default function useFetchAllData(id) {
const [ data, setData ] = useState()
const [ error, setError ] = useState()
const [ loading, setLoading ] = useState(true)
useEffect(() => {
//define a async function to fetch data
const fetchData = async () => {
//The base URL of the API found in the .env file of the app
const url = process.env.REACT_APP_API_URL
//Endpoints correponding to each property we need to fetch data from
const endpoints = {
user: `user/${id}`,
activity: `user/${id}/activity`,
averageSessions: `user/${id}/average-sessions`,
performance: `user/${id}/performance`,
}
try {
//if the REACT_APP_MOCK_DATA variable in the .env file is set to 'true'
//the data is taken from a file that mock the return of the API
if(process.env.REACT_APP_MOCK_DATA === 'true'){
if(id === '18' || id === '12'){
setData(mockApi)
}else{
throw new Error('La page n\'existe pas', { cause: 404 })
}
setLoading(false)
}
//if the REACT_APP_MOCK_DATA variable in the .env file is not set to 'true'
//the data is fetched on the API
else {
if(id){
//initialisation of a contant object to store the data returned by each API endpoints
const fetchedData = {user: '', activity: '', averageSessions: '', performance: ''}
//for each endpoint the data is fetched and added to the fetchedData object
for (const key of Object.keys(endpoints)) {
const response = await fetch(url + endpoints[key])
if(response.ok) {
const { data } = await response.json()
fetchedData[key] = data
} else {
const message = response.status === 404 ? 'La page n\'existe pas' : response.statusText
throw new Error(message, {cause: response.status})
}
}
//Once all data is fetched, set the `data` state with the fetchdData and `loading` state to false
setData(fetchedData)
setLoading(false)
}
//if no id provided throw an error
else {
throw new Error('Une erreur est survenue!', {cause: 500})
}
}
}
//Catch errors during fetch process and set the `error` state with the appropriate message
catch(error) {
if(error instanceof SyntaxError || error.message === 'Failed to fetch') {
setError(new Error('Erreur du serveur', {cause: 500}))
}else{
setError(error)
}
setLoading(false)
}
}
setLoading(true)
//call the function
fetchData()
}, [id])
return { data, error, loading }
}</code></pre>
</article>
</section>
</div>
<nav>
<h2><a href="index.html">Home</a></h2><h3>Modules</h3><ul><li><a href="module-AverageSessionsDuration.html">AverageSessionsDuration</a></li><li><a href="module-Components.html">Components</a></li><li><a href="module-DailyActivity.html">DailyActivity</a></li><li><a href="module-Dashboard.html">Dashboard</a></li><li><a href="module-Error.html">Error</a></li><li><a href="module-KeyDataDisplay.html">KeyDataDisplay</a></li><li><a href="module-Main.html">Main</a></li><li><a href="module-Performance.html">Performance</a></li><li><a href="module-Score.html">Score</a></li></ul><h3>Classes</h3><ul><li><a href="DataModel.html">DataModel</a></li></ul><h3>Global</h3><ul><li><a href="global.html#App">App</a></li><li><a href="global.html#router">router</a></li><li><a href="global.html#useFetchAllData">useFetchAllData</a></li></ul>
</nav>
<br class="clear">
<footer>
Documentation generated by <a href="https://github.com/jsdoc/jsdoc">JSDoc 4.0.2</a> on Fri Mar 10 2023 11:45:23 GMT+0100 (heure normale d’Europe centrale)
</footer>
<script> prettyPrint(); </script>
<script src="scripts/linenumber.js"> </script>
</body>
</html>