Skip to content

Instantly share code, notes, and snippets.

@mithereal
Last active August 30, 2018 23:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mithereal/cbcd561c7fefe315372bd5ea9107b276 to your computer and use it in GitHub Desktop.
Save mithereal/cbcd561c7fefe315372bd5ea9107b276 to your computer and use it in GitHub Desktop.
bs prob reloaded
type state =
| LOADING
| ERROR
| LOADED(string)
type searchType =
| ZIP
| LOCATION
type action =
| FETCHCHANNEL
| FETCHEDWS(string)
| FAILEDTOFETCH
type webSocket = {
id: string
}
module Decode = {
let ws = (webSocket) => Json.Decode.{
id: webSocket |> field("id", string)
}
};
let reducer = (action, _state) =>
switch(action) {
| FETCHCHANNEL => ReasonReact.UpdateWithSideEffects(
LOADING,
(
self =>
Js.Promise.(
Fetch.fetchWithInit(
"/",
Fetch.RequestInit.make(
~method_=Post,
~headers=Fetch.HeadersInit.make({"Content-Type": "application/json"}),
()
)
)
|> then_(Fetch.Response.json)
|> then_(json => json
|> Decode.ws
|> (webSocket => self.send(FETCHEDWS(webSocket.id)))
|> resolve)
|> catch(_err => Js.Promise.resolve(self.send(FAILEDTOFETCH)))
|> ignore
)
),
)
| FETCHEDWS(id) => ReasonReact.Update(LOADED(id))
| FAILEDTOFETCH => ReasonReact.Update(ERROR)
};
let component = ReasonReact.reducerComponent("App");
let make = _children => {
...component,
initialState: () => LOADING,
reducer,
didMount: self => {
self.send(FETCHCHANNEL)
},
render: (self) =>
switch(self.state){
| ERROR => <div> ( ReasonReact.string("An Error Occured !!") ) </div>
| LOADING => <div>
<div> ( ReasonReact.string("Loading... ") ) </div>
</div>
| LOADED(id) => <div>
<Search websocket_id=id />
</div>
}
};
[@bs.module "phoenix"]
open Phx //located at https://github.com/phoenix-china/bucklescript-phx/tree/master/src
type quote = {
id: int,
company: string,
profile: string,
price: int
};
type tQuotes = array(quote)
type state = {
searchType: string,
quotes: tQuotes
}
type action =
| JOINCHANNEL
| ADDQUOTE(quote)
let reducer = (action, state) =>
switch(action) {
| JOINCHANNEL => ReasonReact.Update({...state, searchType: "ZIP"})
| ADDQUOTE(quote) => ReasonReact.Update({...state, quotes: Array.append(state.quotes, [|quote|])})
}
let handleEvent = (self , event, response) => {
self.ReasonReact.send(JOINCHANNEL);
();
};
let component = ReasonReact.reducerComponent("Search");
let make = (~websocket_id: string, _children) => {
...component,
initialState: () => {searchType: "ZIP", quotes: [||]},
reducer,
didMount: (self) =>
{
let socket = initSocket("/socket")
|> connectSocket
|> putOnClose(() => Js.log("Socket closed"))
let channel = socket
|> initChannel(websocket_id);
channel
|> putOn("from_server", handleEvent(self, "from:server"))
|> joinChannel;
},
render: ({state, send}) =>
<Footer />
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment