|
1 |
| -import { useState } from 'react'; |
2 |
| - |
3 | 1 | import Section from '../UI/Section';
|
4 | 2 | import TaskForm from './TaskForm';
|
| 3 | +import useHttp from '../../hooks/useHttp'; |
5 | 4 |
|
6 | 5 | 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(); |
24 | 7 |
|
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 }; |
28 | 11 |
|
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 | + }; |
33 | 14 |
|
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 | + ); |
39 | 27 | };
|
40 | 28 |
|
41 | 29 | return (
|
|
0 commit comments