I'm facing an issue while developing a full-stack JavaScript application that involves asynchronous data fetching. I'm using technologies like Node.js for the backend and React for the front end. The problem arises when I try to fetch data from the backend API asynchronously and update the UI using React components. The data seems to be returning from the API correctly, but it's not rendering as expected in the React components. I have been trying to take help with this site but I have not got any solution till now. Here's an excerpt from my code where I'm trying to fetch data from the backend API and update the React component:
Backend (Node.js - Express):
Frontend (React):
Issue:
Despite the correct data being fetched from the backend API, the UI isn't updating as expected. The <p> element with the text "Data from API: {data}" remains empty or doesn't display the fetched data. I've ensured that the API call is successful and the data is being received. Could this be an issue related to asynchronous rendering in React or some other mistake I'm overlooking?
I appreciate any help in resolving this issue!
Backend (Node.js - Express):
Code:
// server.js
const express = require('express');
const app = express();
const PORT = 3000;
app.get('/api/data', (req, res) => {
// Simulating delay for demonstration
setTimeout(() => {
const data = { message: 'Hello from the backend!' };
res.json(data);
}, 1000);
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Code:
// App.js
import React, { useState, useEffect } from 'react';
import './App.css';
function App() {
const [data, setData] = useState('');
useEffect(() => {
async function fetchData() {
try {
const response = await fetch('/api/data');
const result = await response.json();
setData(result.message);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchData();
}, []);
return (
<div className="App">
<h1>Full Stack App Issue</h1>
<p>Data from API: {data}</p>
</div>
);
}
export default App;
Despite the correct data being fetched from the backend API, the UI isn't updating as expected. The <p> element with the text "Data from API: {data}" remains empty or doesn't display the fetched data. I've ensured that the API call is successful and the data is being received. Could this be an issue related to asynchronous rendering in React or some other mistake I'm overlooking?
I appreciate any help in resolving this issue!