Skip to content

Commit c02a926

Browse files
committed
Using The Custom Hook In More Components
1 parent cdd4de3 commit c02a926

File tree

1 file changed

+19
-31
lines changed

1 file changed

+19
-31
lines changed

src/components/NewTask/NewTask.js

Lines changed: 19 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,29 @@
1-
import { useState } from 'react';
2-
31
import Section from '../UI/Section';
42
import TaskForm from './TaskForm';
3+
import useHttp from '../../hooks/useHttp';
54

65
const NewTask = (props) => {
7-
const [isLoading, setIsLoading] = useState(false);
8-
const [error, setError] = useState(null);
9-
10-
const enterTaskHandler = async (taskText) => {
11-
setIsLoading(true);
12-
setError(null);
13-
try {
14-
const response = await fetch(
15-
'https://react-http-89353-default-rtdb.europe-west1.firebasedatabase.app/tasks.json',
16-
{
17-
method: 'POST',
18-
body: JSON.stringify({ text: taskText }),
19-
headers: {
20-
'Content-Type': 'application/json',
21-
},
22-
}
23-
);
6+
const { isLoading, error, sendRequest: sendTaskRequest } = useHttp();
247

25-
if (!response.ok) {
26-
throw new Error('Request failed!');
27-
}
8+
const createTask = (taskText, taskData) => {
9+
const generatedId = taskData.name; // firebase-specific => "name" contains generated id
10+
const createdTask = { id: generatedId, text: taskText };
2811

29-
const data = await response.json();
30-
31-
const generatedId = data.name; // firebase-specific => "name" contains generated id
32-
const createdTask = { id: generatedId, text: taskText };
12+
props.onAddTask(createdTask);
13+
};
3314

34-
props.onAddTask(createdTask);
35-
} catch (err) {
36-
setError(err.message || 'Something went wrong!');
37-
}
38-
setIsLoading(false);
15+
const enterTaskHandler = async (taskText) => {
16+
sendTaskRequest(
17+
{
18+
url: 'https://react-http-89353-default-rtdb.europe-west1.firebasedatabase.app/tasks.json',
19+
method: 'POST',
20+
headers: {
21+
'Content-Type': 'application/json',
22+
},
23+
body: { text: taskText },
24+
},
25+
createTask.bind(null, taskText)
26+
);
3927
};
4028

4129
return (

0 commit comments

Comments
 (0)