return value from object function inside a map

660 Views Asked by At

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

2

There are 2 best solutions below

2
On

You need to use filter as there you need to return array which satisfy condition.

//...
const getUserName = (userNumber: number, usersArray: [Users]) => {
    return () => {
        usersArray.filter((item) => item.id === userNumber)
                  .map(item => item.name)
        });
    };
};
//...
0
On

This worked in the end, but it doesn't show the item.name value in my component on page load, only if I route away and come back, something to do with my useEffect and dispatch.

const getUserName = (userNumber: number, usersArray: [Users]) => {
        return usersArray.filter((item) => item.id === userNumber).map((item) => item.name);
    };