Reputation: 190
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
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:
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