I'm trying to create a module for XMLHttpRequest that I can call in Reason.useEffect
. The code below I've tried in a single instance and seems to work, but I'd like to be able to hand Reason.useEffect
the ability to call the library's "abort": right now I'm giving it None
so React
doesn't do anything if there's a problem.
type request;
type response;
[@bs.new] external makeXMLHttpRequest: unit => request = "XMLHttpRequest";
[@bs.send] external addEventListener: (request, string, unit => unit) => unit = "addEventListener";
[@bs.get] external response: request => response = "response";
[@bs.send] external open_: (request, string, string) => unit = "open";
[@bs.send] external setRequestHeader: (request, string) => unit ="setRequestHeader";
[@bs.send] external send: request => unit = "send";
[@bs.send] external abort: request => unit = "abort";
[@bs.scope "JSON"][@bs.val] external parseResponse: response => {. "message": array(string)} = "parse";
let send = (~responseCB, ~errorCB, ~apiURL) => {
let request = makeXMLHttpRequest()
request->addEventListener("load", () => responseCB( (request->response->parseResponse)##message ) )
request->addEventListener("error", () => errorCB())
request->open_("GET", apiURL)
request->send
/* How do I return the "request->abort" method as an option? */
/* Some(request->abort) */
None
}
I invoke the above with:
let responseCB = (response) => setState(_previousState => LoadedDogs(response));
let errorCB = () => setState(_previousState => ErrorFetchingDogs);
React.useEffect0(
() => XMLHttpRequest.send(
~responseCB,
~errorCB,
~apiURL="https://dog.ceo/api/breeds/image/random/3"
)
);
I'm very new to FP having been a C jocky for 30+ years.
If I understand correctly, since you're not saying what error you get if you try doing "the obvious", the problem is that React.useEffect0
expects an option(unit => unit)
while Some(request->abort)
would execute request->abort
immediately and return option(unit)
.
If so, the solution should just be to create a unit => unit
function that simply calls request->abort
when invoked:
Some(() => request->abort)