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 ()
}
CodePudding user response:
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)
);