A set of commonly used commands/effects for raj programs.
npm install --save raj-commands
Available commands
import*asCmdfrom'raj-commands'
Cmd.none()
Cmd.ofMsg(nextMessage)
Cmd.promise({
value: somePromise,
resolved:value=> nextMessageA
rejected:error=> nextMessageB
})
Cmd.batch([ cmdA, cmdB, cmdC ]);
Cmd.map(otherCmd,prevMessage=> nextMessage)
Cmd.fetchJson({
url:'/end-point',
success:deserializedJsonResponse=> nextMessageA
error:fetchError=> nextMessageB
})
Cmd.postJson({
url:'/post-end-point',
data:{ some:"data"},
success:deserializedJsonResult=> nextMessageA,
error:fetchError=> nextMessageB
})
Cmd.none() the command that does nothing, although commands are optional in raj, this makes the return type explicit and consistent with the type of the update function.
import*asCmdfrom'raj-commands'
constinit=function(){
let intialState ={ count:0}
let initialCmd =Cmd.none()
return[initialState, initialCmd];
}
Cmd.ofMsg(nextMessage): a command that dispatches the given message directly to the dispatch loop. Although you could just use recursion to call the update directly with your next message, this personally feels a natural way to jump to a different state using the given message/transition:
import*asCmdfrom'raj-commands'
constupdate=function(msg,state){
returnAppMsg.match(msg,{
SubmitSaveChanges:()=>{
if(validate(state)){
return[state,Cmd.ofMsg(AppMsg.SaveChanges())];
}else{
return[state,Cmd.none()];
}
},
SaveChanges:()=>{
/* ... */
},
DataSaved:saveResult=>{
/* ... */
},
DoNothing:()=>[state,Cmd.none()]
})
}
Cmd.map(cmd, msg -> msg): returns a new command/effect that dispatches a transformed message to a different type of message.
Cmd.promise(options) dispatches messages that result from a promise being resolved or rejected:
constnextCmd=Cmd.promise({
value:newPromise((res,rej)=>res(5)),
resolved:value=>AppMsg.ReceivedValue(value),
rejected:ex=>AppMsg.ValueError(ex)
})
return[state, nextCmd];
Cmd.postJson(options) and Cmd.fetchJson(options) are commands that issue POST and GET requests, respectively, using the fetch API:
// GET request
constloadData=Cmd.fetchJson({
url:"/where-my-data-is",
success:data=>AppMsg.DataLoaded(data),
error:err=>AppMsg.DataLoadError(err)
})
// POST request
constsendData=Cmd.postJson({
url:"/secure-endpoint",
data:{ SecurityToken:"..."},
success:result=>{
// result is the deserialized JSON data from server