I have the following question: I’m quite new to Node.js and I want to figure out how to build a simple REST-API that send mock-data to React. In react I then want to fetch the data and render it in a list.
This is what I have so far
Node.js:
const Joi = require("@hapi/joi");
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
app.use(express.json());
const posts = [
{
id: 1,
heading: "post 1",
text: "This is a blogpost"
},
{
id: 2,
heading: "post 2",
text: "This is also blogpost"
}
];
app.get("/api/posts", (req, res) => {
res.send(posts);
});
const port = process.env.PORT || 3001;
app.listen(port, () => console.log(`Listening on port ${port}...`));
My React code:
import React, { useState, useEffect } from "react";
const PostList: React.FC = () => {
useEffect(() => {
fetchItems();
}, []);
const [items, setItems] = useState([]);
const fetchItems = async () => {
try {
const data = await fetch("http://localhost:3001/api/posts");
const items = await data.json();
// console.log("HELLO FROM INSIDE OF FETCHITEMS", items);
setItems(items);
} catch (error) {
console.error(error);
}
};
console.log("STATE", items);
return (
<>
{items.map((item, index) => (
<h1 key={index}>{item}</h1>
))}
</>
);
};
export default PostList;
So what I'm trying to do is to:
- Send the mock-data blog posts from my node.js server
- Fetch the server url ./api/posts
- Save the fetch json objects in a empty state array (items: [])
- Render them out in my render function
I think I have most of it setup but when I try to do this I get this error.
I'm guessing that I have to save all of my objects inside of an array but how would I do that? I thought that I already did that from the node server posts=[].
This is what I get when i console.log state after it's been set.

Do I do it on the backend or the frontend? How would you approach this and am i thinking of this the right way?
Thanks beforehand, Erik

<h1 key={index}>{item}</h1>hereitemis probably anObject, so React can not render that. It should either be a string/number or a JSX element.