redux-saga: race between action and event channel - ecmascript-6

I want to race between a redux action and an event channel using redux-saga.
export function * createEventChannel () {
return eventChannel(emit => {
MyModule.addEventListener(MyModule.MY_EVENT, emit)
return () => { MyModule.removeEventListner(MyModule.MY_EVENT, emit)}
})
}
....
function * raceWithActionAndEvent() {
const channel = yield call(createEventChannel)
// I want to race between Redux Action: 'MY_ACTION' and channel here
}

This should do it:
export function* raceWithActionAndEvent() {
const channel = yield call(createEventChannel);
const winner = yield race({
channel: take(channel),
action: take(MY_ACTION),
});
if (winner.action) {
// then the action was dispatched first
}
if (winner.channel) {
// then the channel emitted first
}
}
In my opinion the code is quite readable. You set up a race between two takes and act on whichever wins.
Please note,createEventChannel doesn't need to be a generator function (like you have in the original question)

Related

Why does the ToolController's getPriority return 0 for my tool?

According to a prior SO answer, you can implement getPriority for a forge viewer Tool. And according to another SO answer extending the ToolInterface does not work. Hence, me not extending the ToolInterface implementing my Tool like so:
class MyCustomExtension extends Autodesk.Viewing.Extension {
constructor(viewer, options) {
super(viewer, options);
this.theiaUtil = new TheiaUtil(this);
}
getPriority() {
console.log("Theia#getPriority called! ", (this.getPriority && this.getPriority() || 0));
return 100000;
}
...
}
My tool's priority is returned as 0 in the ToolController, although it shouldn't:
function getPriority(tool)
{
return tool.getPriority instanceof Function && tool.getPriority() || 0;
}
I don't know why this function returns 0 as tool.getPriority instanceof Function returns true if I call MyCustomExtension.getPriority myself.
Note that ToolInterface is implemented like so:
function ToolInterface()
{
this.names = [ "unnamed" ];
this.getNames = function() { return this.names; };
this.getName = function() { return this.names[0]; };
this.getPriority = function() { return 0; };
this.register = function() {};
this.deregister = function() {};
this.activate = function(name, viewerApi) {};
this.deactivate = function(name) {};
this.update = function(highResTimestamp) { return false; };
this.handleSingleClick = function( event, button ) { return false; };
this.handleDoubleClick = function( event, button ) { return false; };
this.handleSingleTap = function( event ) { return false; };
this.handleDoubleTap = function( event ) { return false; };
// ...
}
Because of that, simply extending the ToolInterface class won't work because all these properties and functions added to the instance in the constructor will take precedence over your actual class methods. This is also likely the reason why you're seeing the priority value returned as zero - when you call myTool.getPriority(), you are not actually calling your getPriority method, but rather the default function which was assigned to this.getPriority in ToolInterface's constructor.
To work around this issue I would recommend explicitly deleting the corresponding fields in your class' constructor (something I explain in my blog post on implementing custom Forge Viewer tools):
class DrawTool extends Autodesk.Viewing.ToolInterface {
constructor() {
super();
this.names = ['box-drawing-tool', 'sphere-drawing-tool'];
// Hack: delete functions defined *on the instance* of the tool.
// We want the tool controller to call our class methods instead.
delete this.register;
delete this.deregister;
delete this.activate;
delete this.deactivate;
delete this.getPriority;
delete this.handleMouseMove;
delete this.handleButtonDown;
delete this.handleButtonUp;
delete this.handleSingleClick;
}
register() {
console.log('DrawTool registered.');
}
deregister() {
console.log('DrawTool unregistered.');
}
activate(name, viewer) {
console.log('DrawTool activated.');
}
deactivate(name) {
console.log('DrawTool deactivated.');
}
getPriority() {
return 42; // Or feel free to use any number higher than 0 (which is the priority of all the default viewer tools)
}
// ...
}
TL;DR: Activate the tool in button click event from a toolbar button instead of the extension's load method.
class MyExtension extends Autodesk.Viewing.Extension {
...
onToolbarCreated(toolbar) {
const MyToolName = 'My.Tool.Name'
let button = new Autodesk.Viewing.UI.Button('my-tool-button');
button.onClick = (e) => {
const controller = this.viewer.toolController;
if (controller.isToolActivated(MyToolName)) {
controller.deactivateTool(MyToolName);
button.setState(Autodesk.Viewing.UI.Button.State.INACTIVE);
} else {
controller.activateTool(MyToolName);
button.setState(Autodesk.Viewing.UI.Button.State.ACTIVE);
}
};
}
...
}
I activated the tool instantly after registering it in the Extension's load method. Petr Broz's github repo from his blog post loads the tool from a button in the toolbar. So I moved the activation of the tool to a button click in the toolbar which worked for me.

useSelector function is not updating the state of after dispatch function -react hooks

I am performing an authentication module where I when I click the sign in button , I am verifying user present is MySQL db or not . I am dispatching the function in here in sign in page
Basically when I dispatch it , the null state of the rSignedIn is not changed immediately after dispatch function. I am completely using react hooks. Please help me solve this , I have been trying this for three days.
But the rSignedIn state value updates when I click the login button again, in general , the when I use the state value using the useSelector the value is updated the second the time when the handleLogin() is invoked
//Sign in Page
...
...
const status=useSelector((state)=>state);
...
...
const handleLogin=(event)=>{
dispatch(LoginUser(loginData));
console.log(status.auth.rSignedIn);
if(status.auth.rSignedIn){
console.log("LOGIN success");
History.push('/');
}else{
console.log("LoginFailed") ;
}
}
this is the action index page where I sent a request to MySQL db , then if there is a response I am dispatching it else an error.
export const LoginUser=(loginData)=>async(dispatch)=>{
await mysqlDB.post('/fetch/retreive',loginData)
.then((response)=>dispatch({type:ActionTypes.LOGIN_SUCCESS,payload:response.data}))
.catch((error)=>dispatch({type:ActionTypes.LOGIN_FAILED}))
}
This is my Reducer for this :
const initialState = {
gSignedIn:null,
userId:null,
registered:null,
data:null,
rSignedIn:null,
}
export default (state=initialState,action)=>{
switch (action.type){
case ActionTypes.GSIGN_IN:
return {...state,gSignedIn:true,userId: action.payload};
case ActionTypes.GSIGN_OUT:
return {...state,gSignedIn:false,userId:null};
case ActionTypes.REGISTER_SUCCESS:
return {...state,registered:true,data: action.payload};
case ActionTypes.REGISTER_FAILED:
return {...state,registered:false,data:null};
case ActionTypes.LOGIN_SUCCESS:
return {...state,rSignedIn:true,data: action.payload};
case ActionTypes.LOGIN_FAILED:
return {...state,rSignedIn:false,data:null};
case ActionTypes.LOGOUT:
return {...state,rSignedIn:false,data:null};
default:
return state;
}
};
dispatch will not update your state value immediately. State value is bound by closure and will only update in your next render cycle.
You can either use history.push within your action or make use of useEffect
const handleLogin=(event)=>{
dispatch(LoginUser(loginData, History));
}
...
export const LoginUser=(loginData, history)=>async(dispatch)=>{
await mysqlDB.post('/fetch/retreive',loginData)
.then((response)=>{
dispatch({type:ActionTypes.LOGIN_SUCCESS,payload:response.data}));
history.push('/')
}
.catch((error)=>{
dispatch({type:ActionTypes.LOGIN_FAILED}))
}
}
With the useEffect, you need to run the it only on change and not on initial render
const initialRender = useRef(true);
useEffect(() => {
if(!initialRender.current) {
if(state.auth.rSignedIn) {
history.push('/');
} else {
console.log(not signed in);
}
} else {
initialRender.current = false;
}
}, [state.auth.rSignedIn])

Promises and garbage collection

I have setup a project with react-redux and I use redux-thunk in my action-creators to do fetching. Here is an example of my thunk:
export const doPostRequest = id => {
return (dispatch, getState) => {
const { id : initiailId } = getState().currentSelection
return api.post(id).then(response => {
if (!isEqual(initialId, getState().currentSelection.id)){
return;
}
dispatch(someOtherAction(id))
return Promise.resolve(true)
})
.catch(err => {})
}
}
As you can see i want to escape the doPostRequest if the currentSelection of my state is changed by the time the response is receieved. Otherwise I return Promise.resolve(true) so the onSubmit in MyComponent can reset the form:
Inside a component (which is a form) i have the following for onSubmit:
class MyComponent extends React.PureComponent{
onSubmit = id => {
this.props.dispatch(doPostRequest(id))
.then(shouldReset => shouldReset && resetForm())
}
render(){
return <form onSubmit={this.onSubmit}>.....</form>
}
}
In most cases, when I really dont have to do anything else except fetching values, I dont do a Promise-chain on the thunk, even though it returns a promise, but here I need to do a resetForm once the postrequest is a success.
Is this implementation good enough, also when it comes to GC ? How are Promises garbage collected ? Is there a problem if I return a fetch().then() without chaining it further?

addEventListener, best way in terms of performance to pass variable to listener

there are three ways of passing data to the listener while using addEventListener in JavaScript. Which one is the most efficient performance wise? Which one do you prefer?
1st Way: With simple listener
// With simple listener
const onBoardBtn = (instructionId) => {
const onBoardBtn = document.querySelector(`.got-it-btn-${instructionId}`);
onBoardBtn.instructionId = instructionId;
onBoardBtn.addEventListener("click", openNextWindow);
}
const openNextWindow = (event) => {
console.log("With Simple Listener: ", event.target.instructionId);
}
export { onBoardBtn };
Is there another way here to pass parameters to the listener?
2nd Way: Event listener with anonymous function
const onBoardBtn = (instructionId) => {
const onBoardBtn = document.querySelector(`.got-it-btn-${instructionId}`);
onBoardBtn.addEventListener("click", function(){openNextWindow(instructionId)} );
}
function openNextWindow(instructionId) {
console.log("With Anonymous function: ", instructionId);
}
export { onBoardBtn };
3rd Way: Event listener with an arrow function
const onBoardBtn = (instructionId) => {
const onBoardBtn = document.querySelector(`.got-it-btn-${instructionId}`);
onBoardBtn.addEventListener("click", () => { openNextWindow(instructionId); } );
}
function openNextWindow(instructionId) {
console.log("with an arrow function: ", instructionId);
}
export { onBoardBtn };
I hope for a nice debate so that we all can learn.
Thanks a lot.

Using redux-saga with setInterval - how and when to yield

Having just moved from thunks to sagas I'm trying to find the best way to call setTimeout and then from within that function call another function (in this case corewar.step()). This was my original code which works as I'd expect.
runner = window.setInterval(() => {
for(let i = 0; i < processRate; i++) {
corewar.step()
}
operations += processRate;
}, 1000/60)
This code is inside a saga and I believe that I should be able to wrap function calls within call as I've done in other areas in the application.
I've tried wrapping the setInterval call in a call and leaving everything else as it is, which results in step() never being called.
runner = yield call(window.setInterval, () => {
for(let i = 0; i < processRate; i++) {
corewar.step()
}
operations += processRate;
}, 1000/60)
I've tried, leaving the setInterval as it is and wrapping the step() function in a call and changing the anonymous function signature to function* which also results in step() never being called.
runner = window.setInterval(function*() {
for(let i = 0; i < processRate; i++) {
yield call([corewar, corewar.step])
}
operations += processRate;
}, 1000/60)
Finally, I've tried wrapping both, which again results in step() never being called.
runner = yield call(window.setInterval, function*() {
for(let i = 0; i < processRate; i++) {
yield call([corewar, corewar.step])
}
operations += processRate;
}, 1000/60)
It feels like I'm missing something here so my question is, should I need to wrap these functions up in call at all or is this wrong?
The follow on question if I am supposed to wrap the outer setInterval in a call would be how should I be defining a function as a parameter to call which also wants to yield either a put or call itself?
There is a section in the saga-redux docs called "Using the eventChannel factory to connect to external events", that suggests using channels.
This section is also providing an example for a setInterval implementation:
import { eventChannel, END } from 'redux-saga'
function countdown(secs) {
return eventChannel(emitter => {
const iv = setInterval(() => {
secs -= 1
if (secs > 0) {
emitter(secs)
} else {
// this causes the channel to close
emitter(END)
}
}, 1000);
// The subscriber must return an unsubscribe function
return () => {
clearInterval(iv)
}
}
)
}
You would then use yield call and yield takeEvery to set it up:
const channel = yield call(countdown, 10);
yield takeEvery(channel, function* (secs) {
// Do your magic..
});
const anotherSaga = function * () {
const runner = yield call(setInterval, () => {
console.log('yes');
}, 1000);
console.log(runner);
}
This works pretty fine for me. In your second snippet there is a double ) at the end where should be only one.
A little late to the party here but this is the top search result for the question of setting a timer in a saga. There's an alternate solution due to the nature of sagas. From here.
I adapted this so:
function* callSelfOnTimer({ value }) {
// Do your work here
...
// If still true call yourself in 2 seconds
if (value) {
yield delay(2000);
yield call(callSelfOnTimer, { value });
}
}
For this to work you also need to add this:
const delay = (ms) => new Promise(res => setTimeout(res, ms))
function* callSelfOnTimer({ value }) {
// Do your work here
...
// If still true call yourself in 2 seconds
if (value) {
yield delay(2000);
yield call(callSelfOnTimer, { value });
}
}