How to correctly create a binding to fetch
with the typed response?
Why not fetch
external binding? Is it so difficult to type fetch
and it’s response?
It’s not super difficult to do a one-off binding: https://github.com/yawaramin/fullstack-reason/blob/70a213e9280cd481d327250733d90693d7246e6c/frontend/ShowBob.re#L3
But it is difficult to do a feature-complete binding of everything that the Fetch API supports (e.g. abort). So IMHO it’s better to reuse the work that’s already been done and tested by others.
I just trying to learn how to work with the language and interop. Thank you.
@yawaramin I looked at your code and at bs-fetch
and didn’t find any code that would show how to type data coming from fetch
response. Is it possible?
It should be. If the response data is JSON serialized to string, then the Fetch API’s Response
class has a json
method which conveniently parses the string into a JSON object. Then, you would have a decoder function to transform the JSON object into a domain-specific type. This is shown in my example. There are a few decoder libraries, e.g.:
- bs-json: allows building decoders by composing together simple components.
- decco: auto-derives a decoder by looking at the shape of the type. Convenient but has some limitations. This is the one I used in my example.
Hi @osenvosem I am also learning ReScript. Here is some simple example code I wrote that fetches and parses JSON data.
This example uses bs-json instead of decco.
@yawaramin didn’t know that it must be decoded. Thank you.
@kevanstannard your post is exactly what I needed. Thank you.