0
async function getDetails() {
        var raw = JSON.stringify({
            "deliveryBoyName": userName,
        });

        const requestOptions = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: raw
        };

        const result = await fetch(apiLink1, requestOptions);
        const jsonResult = await result.json();
        const routedetails = jsonResult.routedetails;

        if (currDetails.length === 0) {
            const promises = routedetails.map(element => {
                const raw1 = JSON.stringify({
                    "deliveryBoyName": "mikey",
                    "deliveryDate": "04-07-2023",
                    "orderPriority": (element.orderPriority + 30).toString()
                });

                const requestOptions1 = {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: raw1
                };

                return fetch(apiLink2, requestOptions1)
                    .then(result => result.json())
                    .then(result => {
                        result = result.routedetails;
                        return result;
                    });
            });

            return Promise.all(promises)
                .then(results => {
                    setCurrDetails([...currDetails, ...results]);
                })
                .catch(error => {
                    console.error(error);
                });


        }

    }


    async function setCurrentIndex() {
        setDeliveryNumber(currDetails[0][0].orderPriority);
        for (let i = 0; i < currDetails.length; i++) {
            if (currDetails[i][0].messagedates.length === 0) {
                setIndex(i);
                setDeliveryNumber(currDetails[i][0].orderPriority);
                break;
            }
        }
    }

    async function setDetails() {
        await getDetails();
        await setCurrentIndex();
    }

    useEffect(() => {
        setDetails();
    }, []);

In the above code actually getDetails() and setCurrentIndex() are main functions that need to be executed to update the data. In getDetails() function the state currDetails gets updated which I need to use in setCurrentIndex() function. With the help of async, await I expect that flow will be as such

getDetails() -> setCurrentIndex()

But it is not happening so, and I got Promise rejection warning. I have been trying this from really long time.

Thank you in advance for the solution.

  • 1
    `setCurrDetails` will not change `currDetails` in the same render cycle, no matter how long you will wait – Konrad Apr 12 '23 at 11:04
  • Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – Konrad Apr 12 '23 at 11:04
  • *"and I got Promise rejection warning*" this means something within your async functions is going wrong ... You should fix that ... Typically there is more infomation on the error in the console log – derpirscher Apr 12 '23 at 11:41

2 Answers2

0

using this code only when first api response come then after setCurrentIndex is called.

async function getDetails(callBack) {
var raw = JSON.stringify({
    "deliveryBoyName": userName,
});

const requestOptions = {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: raw
};

const result = await fetch(apiLink1, requestOptions);
const jsonResult = await result.json();
const routedetails = jsonResult.routedetails;

if (currDetails.length === 0) {
    const promises = routedetails.map(element => {
        const raw1 = JSON.stringify({
            "deliveryBoyName": "mikey",
            "deliveryDate": "04-07-2023",
            "orderPriority": (element.orderPriority + 30).toString()
        });

        const requestOptions1 = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: raw1
        };

        return fetch(apiLink2, requestOptions1)
            .then(result => result.json())
            .then(result => {
                result = result.routedetails;
                return result;
            });
    });

    return Promise.all(promises)
        .then(results => {
            setCurrDetails([...currDetails, ...results]);
            callBack('success')
        })
        .catch(error => {
            console.error(error);
        });


}

}

async function setDetails() {
await getDetails((response) => {
  await setCurrentIndex();
});

}

0

use two different useEffect hooks. the problem is that setCurrDetails will only take effect after a render but you currently assume that it works right away. the comments by Konard are very accurate.

Hasan Aga
  • 718
  • 8
  • 27