I am fetching a pets list from the swagger pets API. I want to remove pets with duplicate ids and then send it to React to avoid the duplicate key problem. I tried the code below but does not work for me. Can anyone help me out with this?
I am new to RxJS so want to remove the commented code which filters distinct objects based on pet id.
export function fetchPetEpic(action$) {
return action$.pipe(
ofType('GET_PETS'),
switchMap(action =>
ajax.getJSON(`https://petstore.swagger.io/v2/pet/findByStatus?status=${action.payload}`).pipe(
map( response => response.map( (pet) => ({
id: pet.id,
pet: pet.pet
}))),
distinct( petList => petList.id),
// map( petList => petList.filter((pet, index, list) => {
// return list.map(petObj =>
// petObj.id).indexOf(pet.id) === index;
// })),
map(response => petActions.setPets(response))
)),
catchError( error => ({ type: 'ERROR_PETS_FETCH', payload: error})),
)
}
Suppose the pets array is something like [ { id: 1, pet: dog}, { id: 2, pet: cat }, { id: 3, pet: fish}, { id: 2, pet: rat }, { id: 4, pet: parrot}, { id: 1, pet: owl } ]
Expected output:[{ id: 1, pet: dog}, { id: 2, pet: cat }, { id: 3, pet: fish}, { id: 4, pet: parrot}]
The output I am getting is the same array as input.
distidnctsay, "Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items." Unless you get a duplicate one right after the other,distinctwon't cut it. In fact-- I think you're better off without. You want to operate on the set as an event, not individual items within the set as events.