Home > database >  How to concat multiple responses and set all response in an array [React JS]
How to concat multiple responses and set all response in an array [React JS]

Time:01-14

I am doing an API call which is returning IDs and based on number of ids I am doing another call and trying to combine the responses but I am stuck with async issues.

const SearchUser = async () => {
    try {
        const response = await getSearchUsers();
        const ids = response.data?.map((user) => user.userId);
        await ids.forEach(async (id) => {
            const result = await getUserInfo(id);
            setRNOUsers(...result);
            // combine result in one state
        });
    } catch (error) {
        setSearching(false);
    }
};

useEffect(() => {
    SearchUser();
    console.log('RNOUsers', RNOUsers); // this is empty and runs even before callng api
}, []);

How can handle this?

CodePudding user response:

You can use Promise.all to wait for all responses, and then set them together with setRNOUsers

const SearchUser = async () => {
    try {
        const response = await getSearchUsers();
        const ids = response.data?.map((user) => user.userId);
        const responses = await Promise.all(ids.map(id => getUserInfo(id)))
        setRNOUsers(...responses.flatMap(x => x));
    } catch (error) {
        setSearching(false);
    }
};

useEffect(() => {
    SearchUser();
    console.log('RNOUsers', RNOUsers);
}, []);

Side note, the problem with console.log('RNOUsers', RNOUsers) is setRNOUsers (initialized by useState) is asynchronous. Besides that, your API calls are also asynchronous, so you cannot get values from RNOUsers immediately in useEffect. If you want to see data in that log, you should wait until the state is updated and your component gets re-rendered with your latest data.

  • Related