React Design Patterns~High Order Components/ Data Loading~



This content originally appeared on DEV Community and was authored by Ogasawara Kakeru

・src/server.js

let users = [
  {
    id: "1",
    name: "Smith",
    age: 55,
    country: "United Kingdom",
    magazines: ["VOGUE-UK", "ELLE"],
  },
  {
    id: "2",
    name: "Michele",
    age: 71,
    country: "United States",
    magazines: ["VOGUE-US", "ELLE"],
  },
  {
    id: "3",
    name: "John",
    age: 43,
    country: "Canada",
    magazines: ["VOGUE-CA", "ELLE"],
  },
];
app.get("/users/:id", (req, res) => {
  const { id } = req.params;
  res.json(users.find((user) => user.id === id));
});

let SERVER_PORT = 8080;
app.listen(SERVER_PORT, () =>
  console.log(`Server is listening on port: ${SERVER_PORT}`)
);

・This file is executed on the server with a command like “node server.js”.

・Install Express.js by running a command like “npm install express” if necessary

・If “Server listening on port: 8080” is displayed on the terminal,
means that the server has been successfully connected.

・src/components/user-info.jsx

export const UserInfo = ({ user }) => {
  const { name, age, country, magazines } = user || {};
  return user ? (
    <>
      <h2>{name}</h2>
      <p>Age: {age} years</p>
      <p>Country: {country}</p>
      <h2>Magazines</h2>
      <ul>
        {magazines.map((magazine) => (
          <li key={magazine}> {magazine} </li>
        ))}
      </ul>
    </>
  ) : (
    <h1>Loading...</h1>
  );
};

This component displays name, age, country, and magazines as user information.

・src/components/include-user.jsx

import { useEffect, useState } from "react";
import axios from "axios";

export const includeUser = (Component, userId) => {
  return (props) => {
    const [user, setUser] = useState(null);

    useEffect(() => {
      (async () => {
        const response = await axios.get(`/users/${userId}`);
        setUser(response.data);
      })();
    });

    return <Component {...props} user={user} />;
  };
};

・This component is a High Order Component.

・This component retrieves user information with axios from the server.

・This component returns a component received as props, passing some props and user information as user props.

・src/App.js

import { includeUser } from "./components/include-user";
import { UserInfo } from "./components/user-info";

const UserInfoWithUser = includeUser(UserInfo, "2");

function App() {
  return (
    <>
      <UserInfoWithUser />
    </>
  );
}

export default App;

・This component returns the UserInfoWithUser component witch is High Order Component wrapped by includeUser passing UserInfo and “2” as variables.

Image description


This content originally appeared on DEV Community and was authored by Ogasawara Kakeru