🌐 Working with Data
Hydrogen has a powerful API for exposing data to your page templates using the data method, we can expose synchronous or asynchronous data.
Let's see how we can do this!
Using Synchronous Data
Synchronous data is any data that does not require some sort of API call to an endpoint.
Using a simple object
const page = ({ title, data }) => `
<html>
<head>
<title>${title}</title>
</head>
<body>
<p>${data.text}</p>
</body>
</html>
`;
module.exports = {
title: 'Hydrogen webpage',
page,
data: ({ dev }) => ({
text: 'Hello from Hydrogen',
}),
};
Using JSON data
const data = require('./data.json');
const page = ({ title, data }) => `
<html>
<head>
<title>${title}</title>
</head>
<body>
<ul>
${data.posts.map((post) => `<li>${post.title}</li>`).join('')}
</ul>
</body>
</html>
`;
module.exports = {
title: 'Hydrogen webpage',
page,
data: ({ dev }) => ({
posts: data,
}),
};
Using Asynchronous Data
Asynchronous data is any data that is sitting in a remote API
Hitting a remote API
const axios = require('axios');
const page = ({ title, data }) => `
<html>
<head>
<title>${title}</title>
</head>
<body>
<p>${data.githubStars}</p>
</body>
</html>
`;
module.exports = {
title: 'Hydrogen webpage',
page,
data: async ({ dev }) => ({
githubStars: await axios.get('https://githubstars.com').then((res) => res.data),
}),
};