13. Exercise: Define a read function
1m

Goal

Define a read function for the numberOfLikes field. By the end, we should have completed our full plan for schema changes in the client and we should see the number of likes showing in the track details page, as shown below:

Track details page with likes showing

Step by step solution

  1. Open up the src/index.js file.

  2. Find the line where we initialized the InMemoryCache for ApolloClient.

    const client = new ApolloClient({
    uri: 'https://workshop-catstronauts-api.herokuapp.com/',
    cache: new InMemoryCache()
    });
  3. Add the properties needed to define the read function. We're targetting the Track type and its numberOfLikes field.

    cache: new InMemoryCache({
    typePolicies: {
    Track: {
    fields: {
    numberOfLikes: {
    read() {
    // TODO - fill in
    }
    }
    }
    }
    }
    }),
  4. In the read function, return a hard-coded number.

    read() {
    return 42;
    }

Full solution

Check your work

Check the app running in localhost:3000 and click on a track.

We should be able to see the number of likes on the page, as shown below:

Track details page with likes showing

The problem is: we can't get it to go up! We'll handle that in the next lesson.

Previous
Next