erikos93
erikos93

Reputation: 687

Render Node.js server data on React frontend

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:

I think I have most of it setup but when I try to do this I get this error.

enter image description here

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. enter image description here

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

Upvotes: 0

Views: 663

Answers (2)

Zachary Maybury
Zachary Maybury

Reputation: 21

Your server is returning an array of type Object. When React renders into the DOM, it will convert your JSX to HTML and thus can only render html primitives. At runtime, your JSX will be injected into the DOM as html that the browser can render. React does not allow Objects as children because because it has no way to convert these into html for the browser. Instead, you need to create valid JSX using the values from the object, which then will be rendered on your page.

Assuming you'd like to render the heading of the post into the h1 and then the content as text after the heading, you can do something like this:

return (
    <>
      {items.map((item) => (
        <div key={item.id}>
            <h1>{item.heading}</h1>
            <p>{item.text}</p>
        </div>
      ))}
    </>
  );

Copyright 2019 DraftKings Inc.
SPDX-License-Identifier: Apache-2.0

Upvotes: 2

PartyLich
PartyLich

Reputation: 319

You need to map your items to something React can render as html.

A simple example would be changing: <h1 key={index}>{item}</h1>

to

<h1 key={index}>{JSON.stringify(item)}</h1>

Without supplying a mapping, React does not inherently know how to represent the object you've passed it. You might also consider defining a 'Post' react fragment to represent your individual posts, and composing them into your PostList

Upvotes: 1

Related Questions