Skip to content

Commit caa6e65

Browse files
committed
Added generic react hook for http requests
1 parent c6f46b6 commit caa6e65

File tree

3 files changed

+92
-7
lines changed

3 files changed

+92
-7
lines changed

Sections/Section 15/04-onwards-to-a-more-realistic-example/src/App.js

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,36 @@
1-
import React from 'react';
1+
import React, { useEffect, useState } from 'react';
22
import Tasks from './components/Tasks/Tasks';
33
import NewTask from './components/NewTask/NewTask';
4-
import useData from './hooks/use-data';
4+
// import useData from './hooks/use-data';
5+
import useHttp from './hooks/use-http';
56

67
function App() {
7-
const { isLoading, taskAddHandler, tasks, fetchTasks, error } = useData()
8+
// For the useData customer React Hook example
9+
// const { isLoading, taskAddHandler, tasks, fetchTasks, error } = useData()
10+
const [tasks, setTasks] = useState([]);
11+
12+
const { isLoading, error, sendRequest: fetchTasks } = useHttp();
13+
14+
useEffect(() => {
15+
const transformTasks = (tasksObj) => {
16+
const loadedTasks = [];
17+
18+
for (const taskKey in tasksObj) {
19+
loadedTasks.push({ id: taskKey, text: tasksObj[taskKey].text });
20+
}
21+
22+
setTasks(loadedTasks);
23+
};
24+
25+
fetchTasks(
26+
{ url: 'https://react-http-e4c37-default-rtdb.firebaseio.com/tasks.json' },
27+
transformTasks
28+
);
29+
}, [fetchTasks]);
30+
31+
const taskAddHandler = (task) => {
32+
setTasks((prevTasks) => prevTasks.concat(task));
33+
};
834

935
return (
1036
<React.Fragment>
@@ -19,4 +45,4 @@ function App() {
1945
);
2046
}
2147

22-
export default App;
48+
export default App;

Sections/Section 15/04-onwards-to-a-more-realistic-example/src/components/NewTask/NewTask.js

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,33 @@
1-
import useData from '../../hooks/use-data';
2-
1+
// import useData from '../../hooks/use-data';
32
import Section from '../UI/Section';
43
import TaskForm from './TaskForm';
4+
import useHttp from '../../hooks/use-http';
55

66
const NewTask = (props) => {
7-
const { isLoading, enterTaskHandler, error } = useData(props)
7+
// const { isLoading, enterTaskHandler, error } = useData(props)
8+
9+
const { isLoading, error, sendRequest: sendTaskRequest } = useHttp();
10+
11+
const createTask = (taskText, taskData) => {
12+
const generatedId = taskData.name; // firebase-specific => "name" contains generated id
13+
const createdTask = { id: generatedId, text: taskText };
14+
15+
props.onAddTask(createdTask);
16+
};
17+
18+
const enterTaskHandler = async (taskText) => {
19+
sendTaskRequest(
20+
{
21+
url: 'https://react-http-e4c37-default-rtdb.firebaseio.com//tasks.json',
22+
method: 'POST',
23+
headers: {
24+
'Content-Type': 'application/json',
25+
},
26+
body: { text: taskText },
27+
},
28+
createTask.bind(null, taskText)
29+
);
30+
};
831

932
return (
1033
<Section>
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { useState, useCallback } from 'react';
2+
3+
const useHttp = () => {
4+
const [isLoading, setIsLoading] = useState(false);
5+
const [error, setError] = useState(null);
6+
7+
const sendRequest = useCallback(async (requestConfig, applyData) => {
8+
setIsLoading(true);
9+
setError(null);
10+
try {
11+
const response = await fetch(requestConfig.url, {
12+
method: requestConfig.method ? requestConfig.method : 'GET',
13+
headers: requestConfig.headers ? requestConfig.headers : {},
14+
body: requestConfig.body ? JSON.stringify(requestConfig.body) : null,
15+
});
16+
17+
if (!response.ok) {
18+
throw new Error('Request failed!');
19+
}
20+
21+
const data = await response.json();
22+
applyData(data);
23+
} catch (err) {
24+
setError(err.message || 'Something went wrong!');
25+
}
26+
setIsLoading(false);
27+
}, []);
28+
29+
return {
30+
isLoading,
31+
error,
32+
sendRequest,
33+
};
34+
};
35+
36+
export default useHttp;

0 commit comments

Comments
 (0)