Renátó Bogár
Renato's blog

Renato's blog

RxJS Pt. 5 - Mapping returned data

RxJS Pt. 5 - Mapping returned data

Renátó Bogár's photo
Renátó Bogár
·May 22, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

If you get the data from the API in the same way as you would like to show it, you have an easy job. However most of the time this is not the case.

Usually when you get the data from an API you want to make some changes, or for example if you make a shopping cart and you want to calculate the gross value of an item which's price appears in net value, you would like to add TAX or VAT on it, which could depend on it's price or the region. Now to stick at the car examples imagine you have a reactive solution on the frontend

private car$ = this.http.get<Car[]>(this.APIURL)
        .pipe(
            tap(response => console.log('Cars: ', JSON.stringify(respose))),
            catchError(this.handleError)
        )
   }

Let's imagine a scenario where the VAT is twenty seven percent, so you would like to modify the data. The following code will not work

private cars$ = this.http.get<Car[]>(this.APIURL)
        .pipe(
            map(car => car * 1.27), //Bad code
            tap(response => console.log('Cars: ', JSON.stringify(respose))),
            catchError(this.handleError)
        )
   }

Since the client gets the car in a wrapper during the http method, we must extract that too, so the correct way to modify the price of the car would look something like this Let's imagine that the price attribute is nullable and do a check on it

private cars$ = this.http.get<Car[]>(this.APIURL)
        .pipe(
            map(cars =>
                cars.map(car => ){
                    ...car,
                    price: car. price ? car.price * 1.27 : 0, 
                    } as Car))),
            tap(response => console.log('Cars: ', JSON.stringify(respose))),
            catchError(this.handleError)
        )
   }

Did you find this article valuable?

Support Renátó Bogár by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this