I'm building a react app where I seed data to a mongoDB database and again fetch that data from that database and render the data to the UI. In this case in the Paintings.js component. However when changes are made to this component the hot-load is activated a spinner is shown but after a few seconds the data is no longer visible in the UI. Only when manually refreshing the page. Sometimes there is this error:
'Proxy error: Could not proxy request /paintings from localhost:3000 to http://localhost:5000/'
I'm running react 17.0.2, scripts 4.0.3
I reinstalled create-react-app, installed nodemon globally, removed the forward slash in the axios get request and added FAST_REFRESH=false to the .env file, no result.
Thank you.
server.js file
const express = require('express');
const app = express();
const cors = require('cors');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const colors = require('colors')
const products = require('./ProductsDB')
const Product = require('./models/paintingsModel')
app.use(cors());
app.use(express.json())
dotenv.config()
// Connect to mongoDB
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.REACT_APP_URL)
console.log(`MongoDB Connected: ${conn.connection.host}`.brightMagenta)
} catch (error) {
console.error(`Error: ${error.message}`.red.bold)
process.exit(1)
}
}
connectDB()
app.get('/', (req, res, next) => {
res.send('API is running...')
})
//Add data to database
const addDataToCollection = async () => {
try {
await Product.deleteMany()
await Product.insertMany(products, function (err, res) {
console.log('Data imported!'.green.inverse)
console.log("Number of documents inserted: " + res.length);
})
} catch (error) {
console.log(error)
}
}
addDataToCollection()
app.use('/', require('./routes/paintingsRoute'))
app.listen(process.env.REACT_APP_PORT, function () {
console.log(`Express server running in ${process.env.NODE_ENV} on port ${process.env.REACT_APP_PORT}`.yellow)
})
package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node backend/server",
"client": "cd frontend && npm start",
"dev": "concurrently \"nodemon backend/server\" \"npm run client\""
},
Paintings.js
import React, { useState, useEffect, useCallback } from 'react'
import './styles.css'
import axios from 'axios'
//import Loader from './Loader'
const Products = () => {
const [paintings, setPaintings] = useState([])
const [loader, setLoader] = useState(true)
const fetchData = useCallback(async () => {
setLoader(true)
try {
await axios.get('paintings').then(res => {
const data = res.data
setPaintings(data)
setLoader(false)
})
} catch (error) {
console.log(error)
setLoader(true)
}
}, [])
useEffect(() => {
fetchData();
return function cleanup() {
fetchData()
};
}, [fetchData])
return (
<div className="paintingsContainer">
{paintings.map(painting => {
const { name, price, _id, imgSrc, artNr } = painting
return (
<div className="products" key={_id}>
<div className="productName">{name}</div>
<div className="price">Price: ${price}</div>
<div className="imageBox">
{!loader ? <img src={process.env.PUBLIC_URL + `${imgSrc}`} alt="item" className="image" /> :
<div className="loaderPng">
<img src={process.env.PUBLIC_URL + '/img/loader.gif'} alt="spinner" className="spinner" style={{ width: "100px" }} />
</div>}
</div>
<div className="footers cart">Add to cart</div>
<div className="footers buy">Buy this product</div>
<div className="footers art">art-nr:{artNr}</div>
</div>
)
})}
</div>
)
}
export default Products