Reputation: 41
Get the fetch function and set it as the state value
I am implementing a component that renders that state value.
export default class HotelComponent {
constructor() {
this.state = {
items: []
}
this.getHotelInfo();
}
async getHotelInfo(){
await fetch('http://localhost:4000/hotel', {method: 'GET'})
.then((response) => response.text())
.then((data) =>{
this.state.items = data
})
this.render();
}
render () {
const { items } = this.state;
console.log(items)
return `
<form id="form">
<p>nation</p><input type="text" name="nation">
<p>hotelNmae</p><input type="text" name="hotelName">
<p>address</p><input type="text" name="address">
<p>tel</p><input type="text" name="tel">
<p>roomType<p><input type="text" name="roomType">
<input type="file" name="file">
<input type="submit">
</form>
<ul>
${items.map((item, key) => `
<li>${item.nation}</li>
<li>${item.hotelName}</li>
<li>${item.address}</li>
<li>${item.tel}</li>
<li>${item.roomType}</li>
<button class="deleteBtn" data-index="${key}">delete</button>
</li>
`).join('')}
</ul>
<button class="addBtn">add</button>
`
}
setEvent () {
this.$target.querySelector('.addBtn').addEventListener('click', () => {
const { items } = this.$state;
this.setState({ items: [ ...items, `item${items.length + 1}` ] });
});
// delete button event
this.$target.querySelectorAll('.deleteBtn').forEach(deleteBtn =>
deleteBtn.addEventListener('click', ({ target }) => {
const items = [ ...this.$state.items ];
items.splice(target.dataset.index, 1);
this.setState({ items });
}))
// to register hotel info
this.$target.querySelector('form').addEventListener('submit', (e) => {
e.preventDefault();
const payload = new FormData(form);
fetch('http://localhost:4000/hotel', {
method: 'POST',
body: payload,
})
.then(res => res.json())
.then(data => console.log(data));
});
}
}
The data is queried just fine.
However,
Uncaught (in promise) TypeError: items.map is not a function
I am getting the same error as below.
How should I solve it?
This is the server file content.
<index.js>
const Hotel = require('./hotel')
...
app.get("/hotel", (req, res)=>{
Hotel.find(function(err, hotel){
if(err) return res.status(500).send({error : 'database failure'});
res.json(hotel);
})
})
<hotel.js>
const mongoose = require('mongoose')
const hotelSchema = new mongoose.Schema({
nation : {type : String},
hotelName : {type : String},
address : {type : String},
tel : {type : String},
roomType : {type : String},
originalFileName : {type : String},
path: {type : String}
});
module.exports = mongoose.model('HotelSchema', hotelSchema)
Upvotes: 0
Views: 1384
Reputation: 36550
I agree with @Andy, that your variable items
looks like a string instead of array.
Try to change from response.text()
to response.json()
see if it works to you.
Upvotes: 1