dimanche 19 juillet 2020

Ember 3.19 Proper way of updating a record and saving it in an API

I have a small Tic Tac Toe game, and I have a scoreboard functionality. I made a Rails API that will hold a global list of these scores.

What is the proper way for me to update the records on my Rails backend from Ember?

Currently what I'm trying to get to work is:

In my application.js route I have

async model() {
    return {
        score: this.store.findAll('score')
    }
}

My game router has

model() {
    return {
      score: this.store.peekAll("score")
    }
  }

In my game.hbs template, I have a button with an onClick sendScore() method in the game.js controller. This method will look at the store for a specific username (users can enter a username under which their scores will be kept in the rails DB), and upon finding the user what it should be doing is setting the scores for this user to be equal to a localStorage item.

sendScore() {
    const entry = this.store.peekAll('score').filterBy("username", localStorage.getItem("username"))[0]
    entry.wins = parseInt(localStorage.getItem("wins"));
    entry.losses = parseInt(localStorage.getItem("losses"));
    entry.draws = parseInt(localStorage.getItem("draws"));
    entry.save();
}

But this doesn't work.

As an example of what currently happens

I start off with a username "damion" that has 150 wins, 146 draws and 318 losses.

If I console.log entry.wins after the entry.wins = parseInt..., the record has clearly updated with whatever is in localStorage. However, upon calling entry.save(), the PATCH request that gets sent out by Ember has values that are unchanged from what it originally was.

What is the proper way of doing this?

EDIT: My Ember Data score model looks like this

import Model, { attr } from '@ember-data/model';

export default class ScoreModel extends Model {
  @attr username;
  @attr wins;
  @attr draws;
  @attr losses;
}

Very simple model. My adapter just has host = localhost:3000 and nothing else in it.

ember-source and ember-data are both version ~3.19.0

I also checked using entry.changedAttributes() in the line before I call my save(), and sure enough Ember can see that I changed my values.

draws: (2) [146, 0]
losses: (2) [318, 5]
wins: (2) [150, 56]



Aucun commentaire:

Enregistrer un commentaire