I'm pretty new to ReactJS so this is my implementation of using Fetch inside of it.
class App extends React.Component {
function postData(url, data) {
// Default options are marked with *
return fetch(url, {
body: JSON.stringify(data), // must match 'Content-Type' header
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, same-origin, *omit
headers: {
'user-agent': 'Mozilla/4.0 MDN Example',
'content-type': 'application/json'
},
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, *same-origin
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // *client, no-referrer
})
.then(response => response.json()) // parses response to JSON
}
render() {
const test_content = ["first", "second", "third"];
const initial_data = {
'id': 1,
'model-name': 'Joke'
};
postData('/start-jokes/', initial_data)
.then(data => console.log(data)
) // JSON from `response.json()` call
.catch(error => console.error(error));
const jokes_div = test_content.map((item, i) => (
<div key={i} className="card col-md-7">
<div className="card-body">
{item}
</div>
</div>
));
return <div className="container" id="jokes">{jokes_div}</div>;
}
}
// ========================================
ReactDOM.render(
<App />,
document.getElementById('root')
);
This works ok and the console logs this response.
Object { status: "ok", jokes: Array[10], ref-id: 11 }
The jokes array has an id and text in an Object, the text would be used same as test_content to populate the items with it's own unique key id shown here
any pointers on how to now populate from there will be much appreciated.
