cross multiple files, a react component to render out the response from an express node app in typescript

To render out the response from an Express Node app in TypeScript, first you need to create a React component. In the component, make an HTTP request to the Node app using Axios. Once the request succeeds, you can set state with the result.

Here's an example App.tsx file:

index.ts
import React, { useState } from "react";
import axios from "axios";

interface ResponseData {
  message: string;
}

const App: React.FC = () => {
  const [data, setData] = useState<ResponseData | null>(null);

  const fetchData = async () => {
    const response = await axios.get<ResponseData>("/api/data");
    setData(response.data);
  };

  return (
    <>
      <button onClick={fetchData}>Fetch data</button>
      {data && <p>{data.message}</p>}
    </>
  );
};

export default App;
490 chars
25 lines

Assuming your Node app is listening on port 3000, the Axios request will be sent to http://localhost:3000/api/data. You'll need to make sure your Node app has a GET /api/data route defined that returns a JSON response with a message property.

Lastly, make sure you have the necessary dependencies installed in your project:

index.ts
npm install axios @types/axios
31 chars
2 lines

And make sure your TS config is configured to allow for imports without extensions:

index.ts
{
  "compilerOptions": {
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "outDir": "dist",
    "baseUrl": ".",
    "paths": {
      "*": ["node_modules/*", "src/types/*"]
    }
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}
322 chars
16 lines

gistlibby LogSnag