Ember Super Rentals Tutorial 3.15 - Working with data - ember.js

I was following the ember Super Rental 3.15 tutorial, when I got to the working with data section, I updated the route index file with model hooks, the page stopped working. Also I am finding ember tutorials to be incomplete.
error says property of map is undefined
code in routes index.js file:
import Route from '#ember/routing/route';
const COMMUNITY_CATEGORIES = [
'Condo',
'Townhouse',
'Apartment'
];
export default class IndexRoute extends Route {
async model() {
let response = await fetch('/api/rentals.json');
let { data } = await response.json();
return data.map(model => {
let { attributes } = model;
let type;
if (COMMUNITY_CATEGORIES.includes(attributes.category)) {
type = 'Community';
} else {
type = 'Standalone';
}
return { type, ...attributes };
});
}
}
image if error message:

Your problem is that fetch('/api/rentals.json'); does not return the correct data. And so when you do let { data } = await response.json(); then data will be undefined and you can not do undefined.map.
So the code you posted is correct. The problem is somewhere else. You can check:
did you correctly add the rentals.json file? If you open http://localhost:4200/api/rentals.json do you see the data? So have you done this?
I see some error from mirage. The super-rentals tutorial does not use mirage. I can see this here (sidenote: that git repo is automatically created from the guides, so its always up to date). So this could be your problem. Depending how you configure mirage it will basically mock all your ajax requests. This means that fetch(... will no longer work then expected, mirage assumes you always want to use mocked data and you did not configure mirage correctly. You can try to remove mirage from your package.json, rerun npm install, restart the ember server and try it again.

Related

How to reload hasMany relationship in ember-data with ember octane?

After upgrading to Ember 3.21.2 from 3.9, reloading hasMany relationships is not working properly anymore. For example the following model hook to fetch editable contents for a user does not update the user model anymore.
model(params) {
const { user } = this.modelFor('application')
const requestParams = this.mapParams(params)
return RSVP.hash({
user,
results: user.hasMany('editableContents').reload({
adapterOptions: requestParams
})
})
},
It still triggers requests, but it loads the same contents with every request, even after the request params have changed. Initially the request is sent to /users/:user_id/editable-contents?filter=......
After changing the adapter options it sends a request for each content to /contents/:content_id
We believe the .reload() function is to blame, because we found out that the .hasMany('editableContents').reload() does not jump to the findHasMany() hook in our application adapter, but instead calls findRecord() for each record.
We are using:
"ember-cli": "~3.21.2",
"ember-data": "~3.21.0"
Any help is appreciated. Thanks!
With the help of user sly7-7 on Ember's Discord server we got pointed in the right direction.
The real problem was that our payload was missing the "related" link, because a paginated payload does not contain that link. A missing related link wasn't a problem before a change in ember-data that implemented the following block that will never be called if payload.links.related is undefined:
if (payload.links) {
let originalLinks = this.links;
this.updateLinks(payload.links);
if (payload.links.related) {
let relatedLink = _normalizeLink(payload.links.related);
let currentLink = originalLinks && originalLinks.related ? _normalizeLink(originalLinks.related) : null;
...
}
see: https://github.com/emberjs/data/blob/ff4f9111fcfa7dd9e39804ed17f5af27a4a01378/packages/record-data/addon/-private/relationships/state/relationship.ts#L633
As a workaround we overrode the normalizeArrayResponse() hook in our application serializer and set the related link to the base request link if there is no related link:
normalizeArrayResponse(store, primaryModelClass, payload, id, requestType) {
if (payload.links && payload.links.first && !payload.links.related) {
const baseLink = payload.links.first.split('?')[0]
if (isRelationshipLink(baseLink)) {
payload.links.related = baseLink
}
}
}
With that workaround, which also uses a rather hacky way to see if the link is a relationship link, the .reload() function works again globally in our application.
To be safe we will also see if we can send the related links with the backend response, which would be cleaner than above workaround.

Apollo client useMutation in expo renders twice for every call

I have a basic expo app with React Navigation.
In the top function Navigation I am initiating a useMutation call to an Apollo server like so:
import { callToServer, useMutation } from '../graphQL';
function Navigation() {
console.log("RENDERED");
const [call] = useMutation(callToServer);
call({ variables: { uid: 'xyz', phoneNumber: '123' } });
...
And my GraphQL settings is as follows:
import {
ApolloClient,
createHttpLink,
InMemoryCache,
useMutation,
} from '#apollo/client';
import { onError } from '#apollo/client/link/error';
import { callToServer } from './authAPI';
const cache = new InMemoryCache();
const httpLink = createHttpLink({
uri: `XXXXXXX/my-app/us-central1/graphql`,
});
const errorLink = onError(({ graphQLErrors, networkError }) => {
...
});
const client = new ApolloClient({
cache,
link: errorLink.concat(httpLink),
});
export {
useMutation,
callToServer,
};
export default client;
I want to clarify that I removed the httpLink from the client setting and I still get the two renders per call. I can see in the console that console.log("RENDERED") prints three times. Once when the app loads (normal) and twice after the useMutation call (not normal?)
What's going on here? Why is react re-renders twice per useMutation call? How do I avoid it?
UPDATE
I did further digging and it seems that useMutation does indeed cause the App to render twice - once when the request is sent, and once when it receives a response. I'm not sure I'm loving this default behavior which seems to have no way to disable. Why not let us decide if we want to re-render the App?
If someone has more insight to offer, Id love to hear about it.
Probably it's too late and maybe you've already found the solution, but still...
As I see you do not need data returned from mutation in the code above. In this case you can use useMutation option "ignoreResults" and set it to "true". So mutation will not update "data" property and will not cause any render.

Aurelia testing components with transient dependencies never uses a mock

We are using the aurelia component testing as defined here (with jest): https://aurelia.io/docs/testing/components#testing-a-custom-element
The component we are testing has a transient dependency. We are creating a mock for this dependency but when we run the tests using au jest, the real one always gets injected by the DI container and never the mock.
Here is the Transient service:
import { transient } from "aurelia-framework";
#transient()
export class ItemService {
constructor() {
}
getItems(): void {
console.log('real item service');
}
}
Here is the 'Mock' service (we have also tried using jest mocks but we get the same result):
import { transient } from "aurelia-dependency-injection";
#transient()
export class MockItemService{
getItems():void {
console.log('mock item service');
}
}
Here is the component under test:
import {ItemService} from "../services/item-service";
import { autoinject } from "aurelia-dependency-injection";
#autoinject()
export class TestElement {
constructor(private _itemService: ItemService) {
}
attached(): void {
this._itemService.getItems();
}
}
Here is the spec file:
import {TestElement} from "../../src/resources/elements/test-element";
import {ComponentTester, StageComponent} from "aurelia-testing";
import {ItemService} from "../../src/resources/services/item-service";
import {MockItemService} from "./mock-item-service";
import {bootstrap} from "aurelia-bootstrapper";
describe('test element', () => {
let testElement;
const path: string = '../../src/resources/elements/test-element';
beforeEach(() => {
testElement = StageComponent.withResources(path).inView(`<test-element></test-element>`);
testElement.bootstrap(aurelia => {
aurelia.use.standardConfiguration();
aurelia.container.registerTransient(ItemService, MockItemService);
});
});
afterEach(() => {
testElement.dispose();
});
it('should call mock item service', async() => {
await testElement.create(bootstrap);
expect(testElement).toBeTruthy();
})
});
But every-time the test is run, the console logs out the real service and not the mock. I have traced this to the aurelia-dependency-injection.js in the Container.prototype.get function. The issue seems to be around this section of code:
var registration = aureliaMetadata.metadata.get(aureliaMetadata.metadata.registration, key);
if (registration === undefined) {
return this.parent._get(key);
}
The registration object seems to be a bit odd, if it was undefined, the code would work as the correct dependency is registered on the parent and it would get the mock dependency. However, it is not undefined therefore it registers the real service in the DI container on this line:
return registration.registerResolver(this, key, key).get(this, key);
The registration object looks like this:
registration = TransientRegistration {_key = undefined}
Is this a bug in aurelia or is there something wrong with what I am doing?
Many Thanks
p.s. GitHub repo here to replicate the issue: https://github.com/Magrangs/aurelia-transient-dependency-issue
p.p.s Forked the DI container repo and added a quick fix which would fix my particular issue but not sure what the knock on effects would be. If a member of the aurelia team could check, that would be good:
https://github.com/Magrangs/dependency-injection/commit/56c7d96a496e76f330a1fc3f9c4d62700b9ed596
After talking to Rob Eisenberg on the issue there is a workaround for this problem. Firstly remove the #transient decorator on the class and then in your app start (usually main.ts) register the class there as a transient.
See the thread here:
https://github.com/Magrangs/dependency-injection/commit/56c7d96a496e76f330a1fc3f9c4d62700b9ed596
I have also updated the repo posted above: https://github.com/Magrangs/aurelia-transient-dependency-issue
to include the fix.
Hopefully this will help any other devs facing the same issue.

Loopback 4: Create seeders to add dummy data in mySQL table

I have been looking around option to create data seeders to add dummy data in my loopback 4 application. However I am not able to find any option in official documentation.
I have found couple of post but those refer to loopback 3, like:
Loopback: Creating a Seed Script
loopback-seed
Please point me out to documentation to do so.
EDIT:
As per suggestion I have created start.js file in scripts folder:
require('babel-register')({
presets: ['es2015']
})
module.exports = require('./seed.js')
And I have copied the script converting it to JavaScript mentioned in seed.js file. When I am running the script, I am getting error:
Cannot find module Models and Repositories
though I have typed correct path.
Actually, I'm doing it with Loopback directly like this (this is typescript):
import * as users from './users.json';
import * as Promise from 'bluebird';
import {Entity, DefaultCrudRepository} from '#loopback/repository';
import {MyApplication} from '../src/application';
import {User} from '../src/models';
import {UserRepository} from '../src/repositories';
const app = new MyApplication();
async function loadByModel<T extends Entity, ID>(items: T[], repository$: DefaultCrudRepository<T,ID>, type: { new(it: Partial<T>): T ;}){
console.log(type.toString());
let repository = await repository$;
await repository.deleteAll();
await Promise.map(items, async (item: T) => {
try{
return await repository.create((new type(item)));
} catch(e){
console.log(item);
}
}, {concurrency: 50});
}
async function load(){
await loadByModel(users, await app.getRepository(UserRepository), User);
}
app.boot().then(async () => {
await load();
console.log('done');
});
We used a separate library db-migrate to keep our migration and seed scripts out of our loopback codebase. Moreso, because db.migrate and db.update methods of juggler are not 100% accurate as mentioned in docs as well. LB4 Database Migrations

Reload model/update template on createRecord save

I see this question is being ask all over again still don't find solution that works for such a trivial task.
This url displays a list of navigations tabs for workspaces.
http://localhost:4200/users/1/workspaces
Each of tab resolves to
http://localhost:4200/users/1/workspaces/:wid
Also on the I have a button that suppose to create a new workspace as well as new tab.
Here how controller for looks:
export default Ember.Controller.extend({
actions: {
newWorkspace: function () {
this.get('currentModel').reload();
var self = this;
var onFail = function() {
// deal with the failure here
};
var onSuccess = function(workspace) {
self.transitionToRoute('dashboard.workspaces.workspace', workspace.id);
};
this.store.createRecord('workspace', {
title: 'Rails is Omakase'
}).save().then(onSuccess, onFail);
}
}
});
When I click on button I see in ember inspector new record indeed created as well as url redirected to id that represents newly created workspace.
My question is how to force model/template to reload. I have already killed 5h trying model.reload() etc. Everything seem not supported no longer. Please please help.
UPDATE
When adding onSuccess
model.pushObject(post);
throws Uncaught TypeError: internalModel.getRecord is not a function
I believe you should call this.store.find('workspace', workspace.id) for Ember Data 1.12.x or earlier. For 1.13 and 2.0 there are more complicated hooks that determine whether or not the browser should query the server again or use a cached value; in that case, call this.store.findRecord('workspace', workspace.id, { reload: true }).
I do not know if this help. I had a similar problem. My action was performed in the route. Refresh function took care of everything.