0

I use reason-apollo to fetch data from server. It returns me data of type (vscode shows me this type):

option(
  Js.t(
    < count : int;
  rows : [ `User of
             < firstName : string; id : string; lastName : string;
               userName : string >
             Js.t
         | `Node of < id : string > Js.t ] option Js.Array.t >
  )
)

I don't really understand type of "rows", and i am not able to get data from that. I tried this:

switch response##users {
   | None => ReasonReact.string("none")
   | Some(data) => {
      data##rows |> Array.map(optionalRow => {
         switch optionalRow {
            | None => ReasonReact.string("none")
            | Some(row) => ReasonReact.string(row##firstName);   
         }
      });
      ReasonReact.string("test");
   }
};

but error is following:

This has type:
  array(option(Js.t(({.. firstName: string} as 'a)))) =>
  array(ReasonReact.reactElement)
But somewhere wanted:
  Js.Array.t(option([ `Node({. "id": string})
                    | `User({. "firstName": string, "id": string,
                              "lastName": string, "userName": string}) ])) =>
  'b

The incompatible parts:
  array(option(Js.t('a)))
  vs
  Js.Array.t(option([ `Node({. "id": string})
                    | `User({. "firstName": string, "id": string,
                              "lastName": string, "userName": string}) ]))
    (defined as
    array(option([ `Node({. "id": string})
                 | `User({. "firstName": string, "id": string,
                           "lastName": string, "userName": string}) ])))

  Further expanded:
    Js.t('a)
    vs
    [ `Node({. "id": string})
    | `User({. "firstName": string, "id": string, "lastName": string,
              "userName": string}) ]

How can I get "firstName" from result?

  • `row` is a polymorphic variant, either `'User` or `'Node`, but you're treating it as an object directly. – glennsl Apr 02 '19 at 14:18

1 Answers1

0

Ahh clear, it's a plymorphic variant, here is snippet how to get the firstName.

...
switch optionalRow {
   | None => ReasonReact.string("none")
   | Some(row) => {
      switch row {
         | `User(u) => ReasonReact.string(u##firstName)
         | `Node(n) => ReasonReact.string("test")
      };
      ReasonReact.string("test");
   }
}
...
  • Note that your example here will always `ReasonReact.string("test")`, since that is the last expression in the `| Some(row)` case. You could instead flatten the nested switches into a single one: ```ReasonReact.string(switch (optionalRow) { | Some(`User(user)) => user##firstName | _ => "test" })``` – Yawar Apr 03 '19 at 14:33