Reputation: 637
I have a React app that is connected to the backend via Express, where I query an SQL database to retrieve data. Final goal is to display that data via React.
Problem
I can't map
through the list of elements returned by the SQL query. I'm too much of a beginner to tell why, but my guess is that it's because the returned data from the SQL query is an object
, and I need an array
to map it. So it returns an error: TypeError: this.state.allwatches.filter is not a function
.
Server.js (seems to be working)
const express = require('express');
const app = express();
const port = 5000;
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : 'password',
database : 'Watches'
});
app.get('/getWatchesList', (req, res) => {
connection.connect();
connection.query('SELECT * from WatchesList', function(err, rows, fields) {
if (!err) {
res.send(JSON.stringify(rows));
} else {
console.log('Error while performing Query.');
}
});
connection.end();
});
app.listen(port, () => console.log(`Server started on port ${port}`));
WatchesList.js (seems to cause problems)
import React, { Component } from 'react';
// Components
import Watche from './WatchesList_Components/Watche.js'
class WatchesList extends Component {
constructor() {
super();
this.state =
{
allwatches : ''
};
}
componentDidMount() {
fetch('/getWatchesList')
.then(res => res.json())
.then(allwatches_ => this.setState({allwatches: allwatches_}, () => console.log("successfully fetched allwatches", allwatches_)))
}
render() {
let filteredWatches = this.state.allwatches.filter((watche) => {
return watche.name.indexOf(this.props.filterText) > -1;
});
return (
<div>
{
filteredWatches.map(
(product) => {
return <Watche name={product.name} price={product.price} image={product.image} />
})
}
</div>
);
}
}
export default WatchesList;
Upvotes: 2
Views: 8188
Reputation: 637
Solved.
I had to replace in server.js res.json(rows);
instead of res.send(JSON.stringify(rows));
, and in my component I had to add an empty array in my state, so I went from allwatches : ''
to allwatches : []
`
Upvotes: 1