We usually use Apex to make callouts from Salesforce. To make call outs from LWC components using Apex we need to use Apex Continuation. However, we can also use fetch API to make a callout from LWC and process the response.
In a way using fetch API to make a callout will be lot more easier and smoother than using Apex Continuation to make the callout.
Let us look at how to make a callout in LWC using fetch API.
Am assuming that you already know how to create a Lightning Web Component. Am not gonna walk you through the whole song and dance of opening VS Code, command patter, SFDX command and etc.
Hope you too are cool with that :p
Here is the template file.
And this is the controller of the Lightning Web Component.
We are using promises here to handle the response that we got back from the callout. Usually there will be some confusion as to why do we need to use the second
.then() in the JS file.
`response.json()` gives us back a promise and not JSON. Now we need to process the process again for which we would need the second
In case you want to use Async Await with fetch API then this is for you, I tried rewriting the same functionality using Async Await.
Simple isn't it. Let me know what you think about this approach.