how to fetch api code example
Example 1: javascript fetch api
fetch('http://example.com/movies.json')
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
});
Example 2: fetch api javascript
fetch('http://example.com/songs')
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));
Example 3: fetch js
async function postData(url = '', data = {}) {
const response = await fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: JSON.stringify(data)
});
return response.json();
}
postData('https://example.com/answer', { answer: 42 })
.then(data => {
console.log(data);
});
Example 4: fetch api javascript
fetch('http://example.com/movies.json')
.then((response) => {
return response.json();
})
.then((myJson) => {
console.log(myJson);
});
Example 5: fetch api tutorial
fetch('https://api.github.com/users/manishmshiva', {
method: "GET",
headers: {"Content-type": "application/json;charset=UTF-8"}
})
.then(response => response.json())
.then(json => console.log(json));
.catch(err => console.log(err));
Example 6: fetch api react
import React, { Component, Fragment } from 'react';
export class FetchJsonController extends Component
{
constructor(props) {
super(props);
this.state = {
data: null,
};
}
componentDidMount() {
fetch(this.props.src)
.then(response => response.json())
.then(data => {
console.log(data);
this.setState({ data })
});
}
render() {
const _data = this.state.data;
const children = React.Children.map(this.props.children, child => {
return React.cloneElement(child, {
jsonData: _data
});
});
return (
<div>{ children }</div>
)
}
}
<FetchJsonController src="somefile.json">
<SomeComponent />
</FetchJsonController>