I'm trying to run a getUserName function that is being called inside an Observable pipe, map, then another map. I can return a single value but I can't seem to map the passed array to then filter out item.name if it matches the id passed in. If I show the code maybe it will be easier to understand:
Not working:
export const fetchDesignsData = (usersArray: [Users]) => (dispatch: Dispatch<Action>) => {
console.log(usersArray);
const DESIGNS_URL = `http://localhost:5000/designs`;
dispatch({
type: "FETCH_DATA_REQUEST",
});
const responsePromise = axios.get(DESIGNS_URL);
const response$ = from(responsePromise);
response$
.pipe(
map((response) => {
const newArray: { name: string; courses: number; wales: number; last_updated: string; by: any }[] = [];
response.data.map((item: { name: any; courses: any; wales: any; updated: any; user_id_last_update: any }) => {
return newArray.push({
name: item.name,
courses: item.courses,
wales: item.wales,
last_updated: item.updated,
by: getUserName(item.user_id_last_update, usersArray),
});
});
dispatch({
type: "FETCH_DATA_SUCCESS",
payload: newArray,
});
})
)
.subscribe();
};
const getUserName = (userNumber: number, usersArray: [Users]) => {
return () => {
usersArray.forEach((item) => {
if (item.id === userNumber) {
return item.name;
}
});
};
};
Basically usersArray looks like this:
[{id: 1, name: "Walter Doe"},
{id: 2, name: "John Doe"}]
so I need to map that array then see if the item.id === userNumber, if yes, return item.name. But it just returns blank every time. Probably because its inside an Observable
You need to use filter as there you need to return array which satisfy condition.