Martin Larocque
Martin Larocque

Reputation: 190

How do I create an API in React

const listApplications = [
    {
        id: 1, // SandboxId
        asset: {
            "id": 1,
            name: "desc", // Asset Name
            desc: "desc",
            currentVersion: {
                id: 1
            }
        },
        screenshot: {
            id: 1,
            currentVersion: {
                id: 1
            }
        }
    }
];


export default class Sandbox extends React.Component<RouteComponentProps<{}>, {}> {
    public render() {
        return <pre>{JSON.stringify(listApplications, null, 2)}</pre>;
    }
}

    componentWillMount() {
        fetch("http://localhost:57833/api/sandbox")
            .then(response => response.json())
            .then(data => console.log(data));
    }

I want a component that returns me a hardcoded array in JSON which I can retrieve through an API.

How do I do that?

This is what I have so far.

Sandbox Component is supposed to return me a hardcoded array in JSON which I can access by fetching it.

Upvotes: 0

Views: 866

Answers (1)

Nino Filiu
Nino Filiu

Reputation: 18493

Don't use React for APIs! An API shall be served directly from the server. It can be achieved in a few lines of code. Example in express:

const express = require('express');

const app = express();
const listApplications = [/* your data here*/];
const port = 57833;

app.get('/api/sandbox', (req, res) => {
  res.json(listApplications);
});
app.listen(port, () => console.log(`Server listening on port ${port}`);

Your fetch('http://localhost:57833/api/sandbox') will never work, because that is how a React app is served:

  1. An .html file is served
  2. Your browser parses the file
  3. This .html file references one or more .js and possibly some .css, .ico, and other files
  4. All files are fetched and served, then runs React's JavaScript code to render the React app
  5. Finally, the app is rendered, possibly including some JSON inside the HTML

And that's the most important point - as a user, you'll might only see the JSON output, but by fetching the file, what is being returned is a very complex HTML+JS object where some JSON is being extracted only after some heavy browser work.

TL;DR don't use React for APIs.

Upvotes: 1

Related Questions