Reputation: 420
I am able to save data into my database. However, i want to know how to show/render the fetch data on my screen after i run my fetch request.
When i add data i am able to push to render on my page. But what i want is, once i run my fetch data function, how do i render the response that i get onto my screen ?
My Json data after fetch looks like this when i console.log(json.data.shipping)
0: { name: "Samsung A10", phone: "001-2342-23429"}
1: {name: "Iphone Xs", phone: "001-12193-1219"}
PS: Beginner with React JS
Below is how i save data
state = {
shippings: userData,
addNewData: {
name: '',
phone: ''
},
};
addData() {
const { name,phone} = this.state.addNewData;
if (name!== '' && phone = "") {
let newData = {
...this.state.addNewData,
id: new Date().getTime()
}
let shippings = this.state.shippings;
fetch( 'http://facicla:5000/api', {
method:'post',
/* headers are important*/
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
body: JSON.stringify(this.state.addNewData)
})
.then(response => {
return response.json();
shippings.push(newData);
NotificationManager.success('Sucess!');
})
}
}
userData
export default [
{
name: 'Shipping-Car',
phone: '001-72342-2342',
} ]
Fetch Data
fetchAllData(){
return this.fetchPost().then(([response,json]) => {
if(response.status === 200)
{
console.log(json.data.shipping)
0: { name: "Samsung A10", phone: "001-2342-23429"}
1: {name: "Iphone Xs", phone: "001-12193-1219"}
}
})
}
fetchPost(){
const URL = 'http://facicla:5000/api';
return fetch(URL, {method:'GET',headers:new Headers ({
'Accept': 'application/json',
'Content-Type': 'application/json',
})})
.then(response => Promise.all([response, response.json()]));
}
Render
render() {
const { shippings, addNewData} = this.state;
return (
<div className="wrapper">
<div className="row row-eq-height">
{shippings.map((shipping, key) => (
<div className="col-sm-3 col-md-3 col-lg-3" key={key}>
<div className="d-flex justify-content-between">
<h5 className="fw-bold">{shipping.name}</h5></a>
<h5 className="fw-bold">{shipping.phone}</h5></a>
</div>
</div>
))}
</div>
}
Upvotes: 0
Views: 99
Reputation: 21691
Try this:
fetchAllData(){
return this.fetchPost().then(([response,json]) => {
if(response.status === 200)
{
console.log(json.data.shipping)
this.setState(
{ shippings: Object.values(json.data.shipping)
//or shippings: json.data.shipping
}
)
//0: { name: "Samsung A10", phone: "001-2342-23429"}
//1: {name: "Iphone Xs", phone: "001-12193-1219"}
}
})
}
Upvotes: 1