So far, we've been fetching data from the server (GET). Now we'll learn to send data to the server - create new resources (POST), update existing ones (PUT), and delete them (DELETE). It's like sending orders from our spaceship to Mission Control.
Each HTTP method has its purpose:
1// GET - Fetch data (default fetch method)
2// POST - Create a new resource
3// PUT - Update an entire resource
4// PATCH - Update part of a resource
5// DELETE - Delete a resourceTo send data to the server, we need to configure the
fetch() options object:1async function createMission(missionData) {
2 const response = await fetch(
3 'https://api.space-center.com/missions',
4 {
5 method: 'POST',
6 headers: {
7 'Content-Type': 'application/json',
8 },
9 body: JSON.stringify(missionData),
10 }
11 );
12
13 if (!response.ok) {
14 throw new Error('Failed to create mission');
15 }
16
17 const newMission = await response.json();
18 return newMission;
19}
20
21// Usage:
22const mission = await createMission({
23 name: 'Alpha Centauri Exploration',
24 crew: ['Captain Nova', 'Dr. Astro'],
25 priority: 'high',
26});The
Content-Type header tells the server what format we're sending data in:1// JSON - most commonly used format
2headers: {
3 'Content-Type': 'application/json',
4}
5
6// Form data
7headers: {
8 'Content-Type': 'application/x-www-form-urlencoded',
9}
10
11// Authorization - access token
12headers: {
13 'Content-Type': 'application/json',
14 'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIs...',
15}1import React, { useState } from 'react';
2
3function MissionForm() {
4 const [name, setName] = useState('');
5 const [destination, setDestination] = useState('');
6 const [submitting, setSubmitting] = useState(false);
7 const [result, setResult] = useState(null);
8 const [error, setError] = useState(null);
9
10 const handleSubmit = async (e) => {
11 e.preventDefault();
12 setSubmitting(true);
13 setError(null);
14
15 try {
16 const response = await fetch(
17 'https://api.space-center.com/missions',
18 {
19 method: 'POST',
20 headers: { 'Content-Type': 'application/json' },
21 body: JSON.stringify({ name, destination }),
22 }
23 );
24
25 if (!response.ok) {
26 throw new Error(\`Error: \${response.status}\`);
27 }
28
29 const data = await response.json();
30 setResult(data);
31 setName('');
32 setDestination('');
33 } catch (err) {
34 setError(err.message);
35 } finally {
36 setSubmitting(false);
37 }
38 };
39
40 return (
41 <form onSubmit={handleSubmit}>
42 <input
43 value={name}
44 onChange={e => setName(e.target.value)}
45 placeholder="Mission name"
46 required
47 />
48 <input
49 value={destination}
50 onChange={e => setDestination(e.target.value)}
51 placeholder="Destination"
52 required
53 />
54 <button type="submit" disabled={submitting}>
55 {submitting ? 'Creating mission...' : 'Create mission'}
56 </button>
57
58 {error && <p className="error">{error}</p>}
59 {result && (
60 <p className="success">
61 Mission "{result.name}" created! ID: {result.id}
62 </p>
63 )}
64 </form>
65 );
66}1async function updateMission(id, updatedData) {
2 const response = await fetch(
3 \`https://api.space-center.com/missions/\${id}\`,
4 {
5 method: 'PUT',
6 headers: { 'Content-Type': 'application/json' },
7 body: JSON.stringify(updatedData),
8 }
9 );
10
11 if (!response.ok) {
12 throw new Error('Update failed');
13 }
14
15 return await response.json();
16}1async function deleteMission(id) {
2 const response = await fetch(
3 \`https://api.space-center.com/missions/\${id}\`,
4 {
5 method: 'DELETE',
6 }
7 );
8
9 if (!response.ok) {
10 throw new Error('Deletion failed');
11 }
12
13 // DELETE often returns 204 No Content (no body)
14 return response.status === 204;
15}
16
17// In a React component
18function MissionItem({ mission, onDelete }) {
19 const [deleting, setDeleting] = useState(false);
20
21 const handleDelete = async () => {
22 if (!window.confirm('Are you sure you want to delete this mission?')) return;
23
24 setDeleting(true);
25 try {
26 await deleteMission(mission.id);
27 onDelete(mission.id);
28 } catch (err) {
29 alert('Error: ' + err.message);
30 } finally {
31 setDeleting(false);
32 }
33 };
34
35 return (
36 <div>
37 <h3>{mission.name}</h3>
38 <button onClick={handleDelete} disabled={deleting}>
39 {deleting ? 'Deleting...' : 'Delete mission'}
40 </button>
41 </div>
42 );
43}