...

/

Updating Song Ratings

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:

Press + to interact
// app/controllers/bands/band/songs.js
import 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;
@action
async 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)
});
}
@action
updateTitle(event) {
this.title = event.target.value;
}
@action
async 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;
}
@action
cancel() {
this.title = '';
this.showAddSong = true;
}
}
...
Access this course and 1400+ top-rated courses and projects.