1//Obj of data to send in future like a dummyDb
2const data = { username: 'example' };
3
4//POST request with body equal on data in JSON format
5fetch('https://example.com/profile', {
6 method: 'POST',
7 headers: {
8 'Content-Type': 'application/json',
9 },
10 body: JSON.stringify(data),
11})
12.then((response) => response.json())
13//Then with the data from the response in JSON...
14.then((data) => {
15 console.log('Success:', data);
16})
17//Then with the error genereted...
18.catch((error) => {
19 console.error('Error:', error);
20});
21
22// Yeah
1fetch('./yourjson.json')
2 .then((response) => response.json())
3 .then((data) => {
4 console.log(data);
5 })
1// This will fetch api.example.com/comments with a header and a body
2fetch(`https://api.example.com/comments`, {
3 method: 'POST', //This could be any http method
4 headers: {
5 'Authorization': 'Basic SGVsbG8gdGhlcmUgOikgSGF2ZSBhIGdvb2QgZGF5IQ==',
6 'Content-Type': 'application/json',
7 },
8 body: JSON.stringify({
9 UID: 58,
10 Comment: "Fetch is really easy!",
11 }),
12})
13.then((response) => response.json())
14.then((newComment) => {
15 // Do something magical with your newly posted comment :)
16});
1componentDidMount() {
2 // GET request using fetch with error handling
3 fetch('https://api.npms.io/v2/invalid-url')
4 .then(async response => {
5 const data = await response.json();
6
7 // check for error response
8 if (!response.ok) {
9 // get error message from body or default to response statusText
10 const error = (data && data.message) || response.statusText;
11 return Promise.reject(error);
12 }
13
14 this.setState({ totalReactPackages: data.total })
15 })
16 .catch(error => {
17 this.setState({ errorMessage: error.toString() });
18 console.error('There was an error!', error);
19 });
20}
1var myHeaders = new Headers();
2
3var myInit = { method: 'POST',
4 headers: myHeaders,
5 mode: 'cors',
6 cache: 'default' };
7
8fetch('flowers.jpg',myInit)
9.then(function(response) {
10 return response.blob();
11})
12.then(function(myBlob) {
13 var objectURL = URL.createObjectURL(myBlob);
14 myImage.src = objectURL;
15});
16
17
1Component with Data
2class App extends React.Component {
3 constructor(props) {
4 super(props);
5 this.state = {
6 items: [],
7 isLoaded: false,
8 };
9 }
10
11 componentDidMount() {
12 fetch('https://jsonplaceholder.typicode.com/posts')
13 .then(res => res.json())
14 .then(result => {
15 this.setState({
16 isLoaded: true,
17 items: result
18 });
19 });
20 }
21
22 render() {
23 const { items } = this.state;
24 if (!isLoaded) {
25 return <div>Loading ... </div>;
26 } else {
27 return (
28 <ul>
29 {items.map(item => (
30 <li key={item.id}>
31 <h3>{item.title}</h3>
32 <p>{item.body}</p>
33 </li>
34 ))}
35 </ul>
36 );
37 }
38 }
39}
40Fetching Data - Ha