Updating Song Ratings
You’ll learn to update the song's rating on the backend in this lesson.
Adding an action handler
The current action that handles clicking a star is dead-simple: it just updates the song’s rating using the set template helper. We’ll need to make it more complicated because it needs to update the song’s rating on the backend, too. This means we’ll have to write an action handler function and make the following changes in the code:
// app/controllers/bands/band/songs.jsimport Controller from '@ember/controller';import { tracked } from '@glimmer/tracking';import { action } from '@ember/object';import Song from 'rarwe/models/song';import { inject as service } from '@ember/service';import fetch from 'fetch';export default class BandsBandSongsController extends Controller {@tracked showAddSong = true;@tracked title = '';@service catalog;@actionasync updateRating(song, rating) {song.rating = rating;let payload = {data: {id: song.id,type: 'songs',attributes: {rating}}};await fetch(`/songs/${song.id}`, {method: 'PATCH',headers: {'Content-Type': 'application/vnd.api+json'},body: JSON.stringify(payload)});}@actionupdateTitle(event) {this.title = event.target.value;}@actionasync saveSong() {let payload = {data: {type: 'songs',attributes: { title: this.title },relationships: {band: {data: {id: this.model.id,type: 'bands'}}}}};let response = await fetch('/songs', {method: 'POST',headers: {'Content-Type': 'application/vnd.api+json'},body: JSON.stringify(payload)});let json = await response.json();let { id, attributes, relationships } = json.data;let rels = {};for (let relationshipName in relationships) {rels[relationshipName] = relationships[relationshipName].links.related;}let song = new Song({ id, ...attributes }, rels);this.catalog.add('song', song);this.model.songs = [...this.model.songs, song];this.title = '';this.showAddSong = true;}@actioncancel() {this.title = '';this.showAddSong = true;}}
As this is a PATCH request, we only need to send the changes: the new rating.
This new updateRating function needs to be called from the template, so let’s make the modification there by removing the @onUpdate={{set song "rating"}} line and adding @onUpdate={{fn this.updateRating song}}:
Access this course and 1500+ top-rated courses and projects.