0

I am using React functional component where I need to make 2 calls to different APIs. My code below hits both the fetcher functions and the result is printed inside. However, the value is not received when in return block. What is wrong here?

The passed URL in useSwr("URL", fectcher) was just a test for a unique key, but that doesn't help either

const fetchOrder = async (cookies, transactionId) => {
    let options = {
        ...
    };
    let headerOptions = {
        ...
    };

    let res = await fetch(Constants.API_ENDPOINT + "/orderdetails", {
        method: "POST",
        body: JSON.stringify(options),
        headers: headerOptions,
    })

     const json = await res.json();
     // console.log(json) // This prints
     return json;
   
};

const handleMatch = async (cookies, transactionId) => {
    let optionsMatch = {
        ...
    };
    let headerOptionsMatch = {
        ...
    };

    let res = await fetch(Constants.API_ENDPOINT + "/match", {
        method: "POST",
        body: JSON.stringify(optionsMatch),
        headers: headerOptionsMatch,
    })

    const json = await res.json();
    // console.log(json) // This prints
    return json;
};

const OrderDetails = () => {
 const { data: matchData, error: matchError} = useSwr(
        "/match",
        handleMatch(cookies, transactionId)
    );
    const { data: orderData, error: orderError } = useSwr(
        "/orderdetails",
        fetchOrder(cookies, transactionId)
    );


    if (!match) return <div>Loading...</div>;
    if (matchError) return <div>Error</div>;
    if (!orderData) return <div>Loading...</div>;
    if (orderError) return <div>Error</div>;
    
    // Doesnt not proceed further from here as data is not received


return ()
}

1 Answer 1

1

I think the problem is from calling function in useSwr they must be function to be returned arrow function will do :

change this :

const { data: matchData, error: matchError} = useSwr(
        "/match",
        handleMatch(cookies, transactionId)
    );

  const { data: orderData, error: orderError } = useSwr(
        "/orderdetails",
        fetchOrder(cookies, transactionId)
    );

to this :

const { data: matchData, error: matchError} = useSwr(
        ["/match",transactionId],
        () => handleMatch(cookies, transactionId)
    );

 const { data: orderData, error: orderError } = useSwr(
            ["/orderdetails",transactionId],
            () => fetchOrder(cookies, transactionId)
        );
Sign up to request clarification or add additional context in comments.

1 Comment

Just before your answer, I figured that out too. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.