Start tracking your progress
Trailhead Home
Trailhead Home
Time Estimate

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.

View of session data in JSON format

Note

Note

We explore other data access strategies in the other projects of this series. For example, in the next project of this series, we get the list of conference sessions from Salesforce using a REST service.

To make this data usable, create a sessionService module that encapsulates the data access logic to retrieve the list of conference sessions.

  1. In the src/client/modules folder, create a new folder named data.
  2. In the data folder, create a folder named sessionService.
  3. In the sessionService folder, create a file named sessionService.js.
  4. 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 cached sessions array. You use this function later in this project when you create the Session Details web component.

  5. 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.