Home > Back-end >  React - call consecutive fetch operations (mtutally dependent)
React - call consecutive fetch operations (mtutally dependent)

Time:08-25

How to call 2 fetch operations where second fetch requires id returned from first call?

My code:

useEffect(() => {
        const fetchData = async () => {
            const aaa=
                await service.getDefaultTemplate();

            const bbb=
                await service.getAnnouncementTemplate({
                    templateId: aaa.id,
                });
            setAaa(aaa); //useState
            setBbb(bbb); //useState
        };
        fetchData().catch(noop)
    }, []);

Only first result aaa is returned, bbb is null

UPDATE

after first answer:

 useEffect(() => {
 service
            .getDefaultAnnouncementTemplate()
            .then((aaa) => {
                setAAA(aaa);
                service
                    .getAnnouncementTemplate({
                        templateId: aaa.id,
                    })
                    .then((bbb) => {
                        setBbb(bbb);
                    })
                    .catch(noop);
            })
            .catch(noop);
}, []);

BUt I get warning: Eslint: avoid nesting promises

CodePudding user response:

to avoid nesting promises warning:

useEffect(() => {
 service.getDefaultAnnouncementTemplate()
 .then((aaa) => {
   setAAA(aaa);
   return service.getAnnouncementTemplate({templateId: aaa.id})
 })
 .then((bbb) => setBbb(bbb))
 .catch(noop);
}, []);

But your snippet with async/await looks good. Check input and output of service.getAnnouncementTemplate method

CodePudding user response:

you can make them dependent with a return, inside the first call you can return any status, maybe an object or something so the code will look like this:

useEffect(() => {
        const fetchData = async () => {
            const aaa=
                await service.getDefaultTemplate();
            if(aaa.status !== "success") return;
            const bbb=
                await service.getAnnouncementTemplate({
                    templateId: aaa.id,
                });
            setAaa(aaa); //useState
            setBbb(bbb); //useState
        };
        fetchData().catch(noop)
    }, []);

that way if the first call is not a success you kill the execution, what you need to do and the vital part is to return any value from the fetch that will tell you its a success or an error

  • Related