0

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.

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

1
  • 2
    <h1 key={index}>{item}</h1> here item is probably an Object, so React can not render that. It should either be a string/number or a JSX element. Commented Dec 9, 2019 at 14:22

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Oh I see! I will look into this. Now there seem to be an error that says Property 'id' does not exist on type 'never'. I'm guessing it's a typescript thing. That also had me confused in the beginning!
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.