Create a Data Service Module
There are many strategies to access data in a JavaScript or web components application. In this step, you create a simple data service module that you can import in any web component to retrieve the list of conference sessions. This module allows us access to our sample data that is hosted in the cloud through a REST service. You can explore the data by using this link to call the endpoint in your browser. Our browser doesn’t render the information in a pretty way, as the data is stored in a JSON format.
To make this data usable, create a sessionService module that encapsulates the data access logic to retrieve the list of conference sessions.
- In the
src/client/modules
folder, create a new folder nameddata
. - In the
data
folder, create a folder namedsessionService
. - In the
sessionService
folder, create a file namedsessionService.js
. - In
sessionService.js
, implement the data service as follows.const URL = 'https://conference-lwc-app.herokuapp.com/api/sessions'; let sessions = []; export const getSessions = () => fetch(URL) .then(response => { if (!response.ok) { throw new Error('No response from server'); } return response.json(); }) .then(result => { sessions = result.data; return sessions; }); export const getSession = sessionId => { return sessions.find(session => { return session.id === sessionId; }); }
The
getSession()
function allows you to retrieve a specific session from the cachedsessions
array. You use this function later in this project when you create the Session Details web component. -
Save the
sessionService.js
file.
That’s it! You created a data service module that you can use to retrieve data anywhere in the
conference application. In the next step, you create a web component that uses the
sessionService
data service to display the list of conference sessions.
We won't check any of your local development. Click Verify Step to go to the next step in the project.