Having promise response inside Vue template interpolation - javascript

I'm using Vue 2 and the composition API. My current component receives a prop from a parent and I render different data based on it, on the screen - the prop is called "result" and is of type Object, containing multiple info. I receive one "result" at a time, but multiple will be rendered - you can think of my "result" as a google search result - which means that the page will have multiple results.
The issue I have is that for one of the info inside "result", I need to call an asynchronous method and display its result, which is what I cannot accomplish.
Currently this is what I have:
<div>
{{ getBoardName(props.result.boardReference) }}
</div>
Method inside the script:
async function getBoardName(boardReference) {
var result = await entriesApi.getBoardName({
boardReference: boardReference,
});
return result;
}
It displays "[object Promise]", although if I console.log(result) right before returning it, it's just what I need, so it seems to me as if the interpolation doesn't actually wait for the promise result.
I've also tried using "then" inside the interpolation:
{{
getBoardName(props.result.boardReference).then((value) => {
return value;
})
}}
I was thinking about using a computed property but I am not sure how that would work, as the response I need from the method has to be connected to each result individually.
Please ask for further clarifications if needed.

As you thought, the interpolation does not actually wait for the result so this is why you have a Promise object.
Since you are using the composition API, what you can actually do is to use a reactive state (using the ref() function if you are waiting for a primitive type, which seems to be the case here, or the reactive() function for objects) and update the state within the onMounted() lifecycle hook.
setup(props, context) {
const boardGameName = ref("");
onMounted(async () => {
boardGameName.value = await getBoardName(props.result.boardReference);
});
async function getBoardName(boardReference) {
var result = await entriesApi.getBoardName({
boardReference: boardReference,
});
return result;
}
return {
boardGameName,
};
}
Since you are dealing with async data, you could add a loading state so you can show a spinner or something else until the data is available.
If your board reference changes over time, you could use a watcher to update your board game name.
Good luck with your project!

Related

Angular subscribes not working how I expect

I'm at a loose end here and trying to understand the flow of how angular subscriptions work.
I make a call to an API and in the response I set the data in a behaviourSubject. So I can then subscribe to that data in my application.
Normally I would use async pipes in my templates cause its cleaner and it gets rid of all the subscription data for me.
All methods are apart of the same class method.
my first try.....
exportedData: BehaviourSubject = new BehaviourSubject([]);
exportApiCall(id) {
this.loadingSubject.next(true)
this.api.getReport(id).pipe(
catchError((err, caught) => this.errorHandler.errorHandler(err, caught)),
finalize(() => => this.loadingSubject.next(false))
).subscribe(res => {
this.exportedData.next(res)
})
}
export(collection) {
let x = []
this.exportCollection(collection.id); /// calls api
this.exportedData.subscribe(exportData => {
if(exportData){
x = exportData
}
})
}
console.log(x)//// first time it's empthy, then it's populated with the last click of data
/// in the template
<button (click)="export(data)">Export</button>
My problem is....
There is a list of buttons with different ID's. Each ID goes to the API and gives back certain Data. When I click, the console log firstly gives a blank array. Then there after I get the previous(the one I originally clicked) set of data.
I'm obviously not understanding subscriptions, pipes and behavior Subjects correctly. I understand Im getting a blank array because I'm setting the behaviour subject as a blank array.
my other try
export(collection) {
let x = []
this.exportCollection(collection.id).pip(tap(res => x = res)).subscribe()
console.log(x) //// get blank array
}
exportApiCall(id) {
return this.api.getReport(id).pipe(
catchError((err, caught) => this.errorHandler.errorHandler(err, caught))
)
}
Not sure about the first example - the placement of console.log() and what does the method (that is assigned on button click) do - but for the second example, you're getting an empty array because your observable has a delay and TypeScript doesn't wait for its execution to be completed.
You will most likely see that you will always receive your previous result in your console.log() (after updating response from API).
To get the initial results, you can update to such:
public exportReport(collection): void {
this.exportCollection(collection.id).pipe(take(1)).subscribe(res => {
const x: any = res;
console.log(x);
});
}
This will print your current iteration/values. You also forgot to end listening for subscription (either by unsubscribing or performing operators such as take()). Without ending listening, you might get unexpected results later on or the application could be heavily loaded.
Make sure the following step.
better to add console.log inside your functions and check whether values are coming or not.
Open your chrome browser network tab and see service endpoint is get hitting or not.
check any response coming from endpoints.
if it is still not identifiable then use below one to check whether you are getting a response or not
public exportReport(collection): void {
this.http.get(url+"/"+collection.id).subscribe(res=> {console.log(res)});
}
You would use BehaviourSubject, if there needs to be an initial/default value. If not, you can replace it by a Subject. This is why the initial value is empty array as BehaviourSubject gets called once by default. But if you use subject, it wont get called before the api call and you wont get the initial empty array.
exportedData: BehaviourSubject = new BehaviourSubject([]);
Also, you might not need to subscribe here, instead directly return it and by doing so you could avoid using the above subject.
exportApiCall(id) {
this.loadingSubject.next(true);
return this.api.getReport(id).pipe(
catchError((err, caught) => this.errorHandler.errorHandler(err, caught)),
finalize(() => => this.loadingSubject.next(false))
);
}
Console.log(x) needs to be inside the subscription, as subscribe is asynchronous and we dont knw when it might get complete. And since you need this data, you might want to declare in global score.
export(collection) {
// call api
this.exportApiCall(collection.id).subscribe(exportData => {
if (exportData) {
this.x = exportData; // or maybe this.x.push(exportData) ?
console.log(this.x);
}
});
}

Angular 8: Run Component Class Methods Synchronously/Sequentially

How do I run methods synchronously in Angular Typescript?
These are not functions, but methods.
First one calls a service, and then second saves into an array.
runTwoMethods()
{
this.validateAddress();
this.saveJsonArchive();
}
Validate address may call more sub-method,may not even be Api, so want to wait until everything completes before saving.
Following syntax is for functions, currently searching for class methods,
Angular / TypeScript - Call a function after another one has been completed
At the end, data is stored into a current data object. And I want to be
save to an archive. Maybe another possibility, how do I keep AddressCurrentMailing and JSONArchive[2] in sync?
Current Data object is sourced from API, not sure where (nor I am not allowed to edit the APIs, then calls transformations), and then would like to save into JsonArchive.
this.jsonArchive[this.jsonArchiveCounter] = this.addressCurrentMailingFinalData
You can use Observable for the 1st and use your 2nd method after Subscribe in callback:
validateAddress(): Observable<Someclassname>
{
return this._http.get<Someclassname>('url');
}
this.yourService.validateAddress().subscribe(
(result) => {
this.saveJsonArchive();
},
(error) => console.log('NO saveJsonArchive'));
EDIT (validateAddress with more one Observable)
const ox: Observable<Someclassname>[] = [];
ox.push(this.http.get<Someclassname>(url1));
ox.push(this.http.get<Someclassname>(url2));
ox.push(this.http.get<Someclassname>(url3));
forkJoin(ox).subscribe(result => this.saveJsonArchive());
You could return a Promise in "this.validateAddress();" and await it.
I assume you use the Angular HttpClient.
For example:
private validateAddress(): Promise<someclassname>
{
return this._http.get<someclassname>("someurl").toPromise()
}
async addSeasonal()
{
await this.validateAddress();
await this.saveJsonArchive();
}
I hope this helps.

use values from observable in angular when they are ready

I'm getting data from observable then manipulating it.
My actual problem is that when I would use data from observable after calling it never get arrived.
But when I console.log result inside subscribe() method at a moment data comes.
I thought that Angular will call again lifecyclehooks when I get data but it's not the case.
refreshData() {
this.apiService.retrieveIndicatorHistory(this.indicatorName, this.currentPeriod).subscribe(res => {
this.values$.push(res);
console.log("values",res)
});
}
ngOnInit() {
this.refreshData();
... few steps after
console.log("values are here", this.values$); // always empty
}
Then I tried to show values inside Onchange also but data never prints
ngOnChanges() {
console.log("values are here", this.values$);
// manipulate data
}
How can I manipulate values that I get from observable when they get ready ?
Should I put all my business logic inside subscribe() ?
RxJS Observable works in async manner, it will emit the data once after it is received. So input and output will be an observable. In order to read the observable data, first you need to subscribe to it.
refreshData() {
this.apiService.retrieveIndicatorHistory(this.indicatorName, this.currentPeriod).subscribe(res => {
this.values$.push(res);
this.processData();
});
}
ngOnInit() {
this.refreshData();
}
processData(){
console.log(this.values$); // you can access data here.
}
You should not put business logic in subscribe. In general, all business logic should be placed in pipe(). And you can subscribe to observable directly in hTML using async pipe.
So in html should be:
<ul *ngFor="let value of (values$ | async)">
<li>{{value}}</li>
</ul>
and inside component.ts:
values = []
values$ = this.apiService.retrieveIndicatorHistory(this.indicatorName, this.currentPeriod).pipe(
map(res => {
this.values.push(res);
return this.values
})
)
Yes, It's an async call and the subscribe will exactly know in time when data arrives, anything in ngOnInit will execute and won't wait for it.
Else you can use (async, await ) combination

Updating a dynamic TD cell in React with promised data

I'm working on building on a dynamic table view for data in React. I'm currently getting the data back through a promise, and I'm trying to update a specific TD with the data returned by said promise. However attempting to do so with jQuery gives me an "unrecognized expression" error. I've read that you shouldn't be using jQuery with React anyways, but I can't seem to wrap my head around how to construct my view correctly (I assume I should be creating a child component, but I'm unsure how to update it with promised data). Here's my current code attempting to accomplish this. Thanks for any help!
getThingField(thing, key) {
const self = this;
var user = gun;
if(typeof(thing[key]) === 'object') { //Field requires a lookup of data
var cellKey = thing._['#'] + self.props.linkedFields[key]
cellKey = cellKey.replace(/\s/g, '');
var jGet = '#' + cellKey;
self.gunGetListProp(user, thing[key]['#'], self.props.linkedFields[key]).then(e=> {
//this is my promise that returns my data in 'e'
if(e.length == 1) {
self.updateTD(jGet, e[0]);
}
else {
//I expect an array of length 1 so I'm skipping this for now
}
});
return <td key={cellKey}></td>; //To ensure the cell always renders
}
else { //This is for fields that don't require a lookup and works properly
return (
<td key={thing._['#'] + key}>{thing[key]}</td>
)
}
}
updateTD(cellKey, val) {
$(cellKey).html(val);
}
The reason you read that you should not use jQuery with React is that they operate on two fundamentally different paradigms. jQuery manipulates the DOM directly, while React responds to changes in state, then manipulates the DOM as needed.
The code that you submitted should be changed so that when the promise returns with your data, you call this.setState (assuming you are within a component class). The class will re-render the table based on the new state. The promise should not be called inside the render() function because that is a pure function. Instead, you can call the promise in a lifecycle method such as componentDidMount().
I would review the state and lifecycle documentation here.

Returning value from an observable operation in angular?

Am working in Angular and the problem seems to be: When I subscribe to the observable in my component, I can console.log() the data successfully, but I cannot assign the data to any afore declared variables and view it in the view template. This is the code: I understand that logging in the console is a synchronous process while the observable subscription in itself is asynchronous, but outputting a value from an asynchronous operation in the view template seems to be the problem. I have seen quite a number of solutions on stack overflow but it does not resolve the problem since it doesn't address this kind of problem.
This is a sample of the code
//The getData function returns an obsverbale
favoriteShirt;
const gtc = this;
gtc.getData().subscribe({
next: (data) => {
console.log(data.favShirtFromStore) // this returns an objects with the shirts (this is a sync op)
gtc.favoriteShirt = data.favShirtFromStore; //this returns undefined <= where the problem is
},
error:(err)=>{console.log(`There was an error ${err}`)},
complete:()=>{console.log("Completed...")}
});;
Why don't you use it like this:
gtc.getData().subscribe(res => {
//whatever you want to do with res
});
here res is returned data from your function and you can use it the way you want, such as assign it to another variable and so on ...

Categories

Resources