Havent been able to reconcile this challenge to the docs :/ Hoping someone can point out to me why when this lwc renders (successfully) and it receives an event via its empApi subscription it throws a 'handleGoNext is not defined' runtime error. I appreciate the function is not visible, but I'm not able to construct things such that a resulting function call is able to be made successfully. Calling this.handleGoNext() doesnt work either. Any pointers would be most appreciated!
handleGoNext(){
// *** this is the logic Im hoping to call ***
};
// Initializes the component
connectedCallback() {
if(this.subscription = {}){
// Callback invoked whenever a new event message is received
const messageCallback = function (response) {
handleGoNext(); // *** THIS IS THE CALL THAT BREAKS THINGS ***
};
// Invoke subscribe method of empApi. Pass reference to messageCallback
subscribe(this.channelName, -1, messageCallback).then((response) => {
// Response contains the subscription information on subscribe call
console.log(
'Subscription request sent to: ',
JSON.stringify(response.channel)
);
this.subscription = response;
});
}
}
what happens when you do subscribe(this.channelName, -1, this.handleGoNext)?
Here's my function from around Easter time, didn't check recently if it still works.
isSubscribed = false;
subscription = {};
replayId;
#track data = [];
subscribe(id) {
const handleMessage = (response) => {
let val = Object.assign({}, response.data.event, response.data.payload);
this.replayId = Math.max(this.replayId ?? 0, val.replayId);
/* do not use this.data.push(val);
it doesn't play well with datatable. Use the spread operator or JSON.parse/JSON.stringify trick.
Plus we want new rows to be added on top of the list.`
*/
this.data = [val, ...this.data];
};
subscribe(this.channel, id, handleMessage).then((response) => {
this.subscription = response;
this.isSubscribed = true;
});
}
Related
I have a lwc component that subscribes to the event WhatsAppMessage, and I have been trying to filter the event platform but I have not been able to get the expected result, since it does not respect my filter and it brings me all the results
This is my JS Code when I suscribe
import { LightningElement } from 'lwc';
import { subscribe, unsubscribe, onError, setDebugFlag, isEmpEnabled } from
'lightning/empApi';
export default class PlatformEventMonitor extends LightningElement {
channelName = '/event/Sample__e';
isSubscribeDisabled = false;
isUnsubscribeDisabled = !this.isSubscribeDisabled;
subscription = {};
// Tracks changes to channelName text field
handleChannelName(event) {
this.channelName = event.target.value;
}
// Initializes the component
connectedCallback() {
// Register error listener
this.registerErrorListener();
}
// Handles subscribe button click
handleSubscribe() {
// Callback invoked whenever a new event message is received
const messageCallback = function(response) {
console.log('New message received: ', JSON.stringify(response));
// Response contains the payload of the new message received
};
// Invoke subscribe method of empApi. Pass reference to messageCallback
subscribe(this.channelName, -1, messageCallback).then(response => {
// Response contains the subscription information on subscribe call
console.log('Subscription request sent to: ', JSON.stringify(response.channel));
this.subscription = response;
this.toggleSubscribeButton(true);
});
}
// Handles unsubscribe button click
handleUnsubscribe() {
this.toggleSubscribeButton(false);
// Invoke unsubscribe method of empApi
unsubscribe(this.subscription, response => {
console.log('unsubscribe() response: ', JSON.stringify(response));
// Response is true for successful unsubscribe
});
}
toggleSubscribeButton(enableSubscribe) {
this.isSubscribeDisabled = enableSubscribe;
this.isUnsubscribeDisabled = !enableSubscribe;
}
registerErrorListener() {
// Invoke onError empApi method
onError(error => {
console.log('Received error from server: ', JSON.stringify(error));
// Error contains the server-side error
});
}}
What makes you think this would work? I don't recognise syntax for filtering like that? From what doc you took it?
You can set replay id to -1, -2 but you'll get all messages. https://developer.salesforce.com/docs/component-library/bundle/lightning-emp-api/documentation
You can filter them out manually in your app but it'll waste the daily limit of the events to can receive...
The proper way would be to define custom channel on top of your event. It's bit like writing a query/listview/report. But there is no UI for it, you'd have to craft a special JSON and send it to ord using tooling API.
https://developer.salesforce.com/docs/atlas.en-us.platform_events.meta/platform_events/platform_events_filter_section.htm
Currently, I am working on my react-native application using MST as a state management library.
Now I have encountered an issue where the app has a chance to fire 2 similar API calls. The 1st API responded after the 2nd one, which caused the data to be overridden by an outdated response.
In redux-saga, we can use takeLatest to make sure we get the data from the latest request. I am looking for similar function in MST to address the problem.
I have found that there's Axios' cancel token to cancel the API calls, but I want to see is there any way in a more generic async way to solve it.
As far as I know there is no build in features like that in MobX or MST, so you would need to implement it by yourself.
Generic way I usually use to cancel promises is this one (credit to https://wanago.io):
class RaceConditionGuard {
private lastPromise: PromiseLike<unknown> | null = null;
getGuardedPromise<T>(promise: PromiseLike<T>) {
this.lastPromise = promise;
return this.lastPromise.then(this.preventRaceCondition()) as Promise<T>;
}
preventRaceCondition() {
const currentPromise = this.lastPromise;
return (response: unknown) => {
if (this.lastPromise !== currentPromise) {
return new Promise(() => null);
}
return response;
};
}
cancel = () => {
this.lastPromise = null;
};
}
And the usage, assuming you have some class based store, for example:
class SomeStore {
raceConditionGuard = new RaceConditionGuard();
loadItems = () => {
// Previous call will be automatically canceled (it will never resolve actually)
this.raceConditionGuard
// Wrap your async operation
.getGuardedPromise(fetchSomething())
// Handle result somehow
.then(this.handleResult);
};
// Or you can cancel manually
cancelLoading = () => {
this.raceConditionGuard.cancel()
}
// ...
}
I am trying to retrieve some data from Yahoo Finance using an XHTML Request, which works. However, I am trying to display the data retrieved on my app, but the method to retrieve the data is returning "undefined" before the data has been loaded.
async componentDidMount() {
var tempData = await this.fetchAsync();
console.log(tempData)
this.handleLoad(tempData)
}
handleLoad = (num) => {
this.setState(state => ({
price: num
}));
}
async fetchAsync () {
const xhr = new XMLHttpRequest();
xhr.withCredentials = true;
const {params} = this.props.navigation.state;
var ticker = params.ticker;
var result;
var tempArray = [1];
var url = "https://yahoo-finance-low-latency.p.rapidapi.com/v8/finance/spark?symbols=" + ticker + "&range=2y&interval=1d"
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
result = JSON.parse(this.responseText);
tempArray = result[ticker]['close'];
testPrice = tempArray[tempArray.length-1]
console.log(testPrice)
var self = this;
return tempArray[tempArray.length-1]
}
});
xhr.open('get', url, true);
xhr.setRequestHeader("x-rapidapi-key", "my key");
xhr.setRequestHeader("x-rapidapi-host", "yahoo-finance-low-latency.p.rapidapi.com");
xhr.send();
}
I am using the componentDidMount() function to begin calling the methods to load the data, but when the app renders, the values are not displayed.
As you can see inside the fetchAsync() method, I return the value I need, but when I try and console.log the return from this method, I get undefined.
I have also tried moving this return to the end of the method, but when I use console.log here to ensure that tempArray has the data I need, it is empty.
I need to display tempArray[tempArray.length-1] on my screen, but the data is not loaded in time, and does not update even after it has loaded.
Your return tempArray[tempArray.length-1] inside the fetchAsync isn't actually returning from fetchAsync -- it's just returning from the callback function inside addEventListener. In fact, you don't actually have any code that is taking advantage of the async tag you have on that function.
One solution to this would be to call handleLoad directly from inside fetchAsync instead of return tempArray. (Of course, you'll want to make sure that you've bound this correctly to handleLoad).
Another solution would be to pass a callback function into fetchAsync that you could call instead of returning. Then, at your call site, it might look something like this:
this.fetchAsync((tempData) => {
console.log(tempData)
this.handleLoad(tempData)
});
Finally, a third solution would be to switch from XMLHTTPRequest to fetch, and then you could take advantage of async/await and actually make that fetchAsync method async (and be able to return a value from it).
I'm new to NodeJS and are only familiar with Java. I'm trying to create a file that creates objects based on a database and adds them to an array. This array I want to be able to export so that I can use it throughout the whole program, but when I try to export the array it doesn't work. I've tried googling and understanding but haven't come across anything that was helpful unfortunately.
I hope that someone can help me understand
I've tried calling module.exports after the ".then" call, but it just returns an empty array because its async.
I've also tried calling module.exports = teams inside the .then call but it didn't work neither.
var teams = [];
function assignTeamsToClasses() {
return new Promise((resolve, reject) => {
getAllTeamsInDb((teamList) => {
teamList.forEach((aTeam) => {
let newTeam = new Team(aTeam['teamid'], aTeam['teamname'], aTeam['teamrank']);
teams.push(newTeam);
});
resolve();
});
})
}
assignTeamsToClasses().then(() => {
module.exports = teams;
});
main.js
var teams = require('./initialize.js');
console.log(teams);
I expect it to return all teams that are in the database. I know that array is not empty when called within the ".then" call, but the export part does not.
Simple
the sequence require() + console.log() is synchronous
assignTeamsToClasses() is asynchronous, i.e. it updates teams at some unknown later point in time.
You'll have to design your module API to be asynchronous, e.g. by providing event listener interface or Promise interface that clients can subscribe to, to receive the "database update complete" event.
A proposal:
module.exports = {
completed: new Promise(resolve =>
getAllTeamsInDb(teams => {
const result = [];
teams.each(aTeam =>
result.append(new Team(aTeam.teamid,
aTeam.teamname,
aTeam.teamrank)
)
);
resolve(result);
})
),
};
How to use it:
const dbAPI = require('./initialize.js');
dbAPI
.completed
.then(teams => console.log(teams))
.catch(error => /* handle DB error here? */);
Every caller who uses this API will
either be blocked until the database access has been completed, or
receive result from the already resolved promise and proceed with its then() callback.
Basically what i try to do is to hit my API once and save the result inside global variable in my Service, and then share and modify this value in my parent and child component with two helpers functions.
repairs.service.ts
public myItems:any[];
public GetRepairs = ():Observable<any> => {
this.headers = new Headers();
this.headers.set('Authorization', 'Bearer' + ' ' + JSON.parse(window.localStorage.getItem('token')));
return this._http.get(this.actionUrl +'repairs'{headers:this.headers})
.map((res) => {return res.json();
}).map((item) => {
let result:Array<any> = [];
if (item.items) {
item.items.forEach((item) => {
result.push(item);
});
}
this.myItems = result;
return this.myItems;
});
};
public GetItems() {
return this.myItems;
};
public UpdateItems(data:any[]) {
this.myItems = data;
};
And then in my main component i do
repairs.component.ts
export class RepairsComponent implements OnInit {
public myItems:any[];
constructor(private _userService:UserService,
private _RepairsService:RepairsService,
public _GlobalService:GlobalService) {
}
ngOnInit() {
this._userService.userAuthenticate();
this.getAllItems();
}
private getAllItems():void {
this._RepairsService
.GetRepairs()
.subscribe((data) => {
this._RepairsService.UpdateItems(data);
},
error => console.log(error),
() => {
this.myItems = this._RepairsService.GetItems();
});
}
}
This work just fine but when i try to invoke GetItems() in child component i get undefinded. I try to do it inside constructor and ngOnInit with the same result.
child.component.ts
export class ChildComponent {
private items:any[] = [];
constructor(private _RepairsService:RepairsService,
private _Configuration:Configuration) {
this.items = this._RepairsService.GetItems();
// undefinded
}
ngOnInit() {
this.items = this._RepairsService.GetItems();
// undefinded
}
}
From what i can see in the limited amount of code you shared, it would seem you are trying to get the items before the http get call finishes and saves the data. I think a better design pattern would be to make the GetItems() function also an observable or promise, and check if the data is there, if not call the http get call, and once that completes send the data back to the different components that need it.
As #MSwehli mentioned with async code execution you can't rely on the order of code lines. In this code:
ngOnInit() {
this.items = this._RepairsService.GetItems();
// undefinded
}
the async code in GetItems(); is scheduled for later execution into the event queue and then continued with the sync code. The scheduled code will be executed eventually but it's not determined when. It depends on the response of the server in this example.
If you return a Promise you can use .then(...) the chain the execution so that your code is only executed when the async execution is completed.
There are two errors/inconsistencies in your code:
userAuthenticate() call followed with getAllItems() call. These calls are async, user is not yet authenticated by the time getAllItems() is called, getAllItems will fail.
Solution here is to chain calls using rxjs flatMap:
//assuming userAuthenticate returns Observable
userService.userAuthenticate().flatMap(()=>{
return repairsService.GetRepairs();
}).subscribe(..process repairs..);
getAllItems() is called nearly at the same time as GetItems(). In most cases it fails also, because previous http request is not completed when GetItems() is called.
In my opinion early initialization is not necessary here, use service directly:
//ChildComponent
ngOnInit() {
this._RepairsService.GetRepairs().subscribe(..do anything with list of repairs i.e. assign to bindable property..);
}
You could add console.log statements in each part of the code to see the order of events in your app.