Redux or Pub/Sub? - react-native

I have a react app which will record audio.
When the user presses a button the component should cause it's parent to run a stopRecording() routine, resulting in saving the file and some json data about conditions and triggering a user flow.
I'd been looking into Redux which seems fine for JSON data but I'm less sure about audio files.
But does Redux fulfill the purpose of pub/sub for notifying components they should do stuff.

But does Redux fulfill the purpose of pub/sub for notifying components
they should do stuff.
Yes. Whenever the store changes, all "connected" components will receive the new store update and consequently componentDidUpdate will get called. So for example, let's say that you would like to trigger an action and listen on that trigger, then you would do something like this:
The subscriber
class MyListenerComponent extends Component {
...
componentDidUpdate(prevProps) {
if(this.props.triggerAction !== prevProps.triggerAction) {
// do something meaningful here, perform user flow, stop recording, whatever
}
}
...
}
const mapStateToProps = (state) => {
return({
triggerAction: state.triggerAction
})
}
export default connect(mapStateToProps)(MyListenerComponent)
The action triggerer (publisher)
this.props.dispatch({type: 'TRIGGER_ACTION', triggerAction: 'some data here'})
The reducer:
switch(action.type) {
case 'TRIGGER_ACTION':
return ({
...state,
triggerAction: action.triggerAction,
})
}

Related

Firebase authentication and redux-saga synchronizing state

I have a design question on how to manage firebase auth & redux saga states with react-native-firebase.
Example use-case
Let's start from the scenario that I have an app that uses the idToken for a variety of use cases, some in the views using information from the claims, and some in redux actions to make api calls.
Using redux-saga, I would expect to implement these two cases like so:
// in selectors.js
const getIdToken = (state) => state.idTokenResult?.token
const getUserRole = (state) => state.idTokenResult?.claims.role
// in view.js
const role = useSelector(Selectors.getUserRole)
// in actions.js
const idToken = yield select(Selectors.getIdToken)
With this in mind I want to make sure the idTokenResult is available & up to date in my state. I can do this we a few actions and reducers, by calling a login method & then relying on the dispatched event onIdTokenChanged to update my state on login & tokenRefreshes. Something like the following:
// in actions.js
function* onLogin(email, password){
yield call([auth(), 'signInWithEmailAndPassword'], email, password)
}
// This action would be called by an eventChannel which emits on each onIdTokenChanged
function* onIdTokenChanged(user){
yield put({ type: "UPDATE_USER", user: user, })
if (user){
const idTokenResut = yield call([auth().currentUser, 'getIdTokenResult'])
yield put({ type: "UPDATE_ID_TOKEN_RESULT", idTokenResult: idTokenResult, })
}
}
// in reducers.js
const reducer = (state = {}, action) => {
switch (action.type) {
case 'UPDATE_USER':
return { ...state, user: action.user };
case 'UPDATE_ID_TOKEN_RESULT':
return { ...state, idTokenResult: action.idTokenResult }
}
}
Problem
Here is when we run into a problem. I recently learned that the onIdTokenChanged is dispatched lazily, only when the getIdTokenResult() method is invoked link. This means that with the code above we cannot expect our state to be accurate, because when we call yield select(Selectors.getIdToken) it doesn't check getIdTokenResult() and therefore the onIdTokenChanged event is never dispatched.
Potential solutions
How do we overcome this problem?
Set up a timer which periodically calls getIdTokenResult() before the token expires, to trigger the event.
Should work, but defeats the purpose of having an onIdTokenChanged event. Also this means it will refresh the token hourly, even if it isn't needed or being accessed
Somehow call getIdTokenResult() in the selector?
It's an async method so it seems like an anti-pattern here and I'm not even sure it's possible
Use the library directly to fetch user states with auth().currentUser, and forget redux-saga
We lose the nice rerender functionalities that redux's useSelector provides. By accessing the state directly we'll need to figure out another way to trigger rerenders on auth changes, which defeats the purpose of using redux-saga
Something I didn't consider/implemented incorrectly?
Your suggestions are welcome and thanks in advance for you help! :)

API response is not accessible in ComponentDidMount but in render I can use

Hi I am working on React Native app. I am using Redux and Saga. I call the API in componentDidMount.
async componentDidMount() {
let data = this.props.navigation.getParam("returnProductData");
if (data) {
console.log("Return Here");
this.props.getProductReturnAction(data)
this.setState({
returnQty:parseInt(this.props.product.item_ordered)-parseInt(this.props.product.already_return_qty)
});
console.log(this.state.returnQty,"Return quty"); //coming undefined
console.log(this.props.product, "product"); // undefined
console.log(this.props.product.item_ordered); //undefined
}
}
I have to set the state in componentDidMount for returnQty. But, state is not accessible here. It's working fine in render method. I can use all the product object. But, it is coming empty in componentDidMount. I tried using async and await but it's not working.
// Dispatch Methods
const mapDispatchToProps = dispatch => {
return bindActionCreators(
{ getProductReturnAction, submitProductReturnAction },
dispatch
);
};
// Props
const mapStateToProps = state => {
return {
product: state.myOrdersReducer.returnProduct
};
};
I can't be able to find out the bug please help to find out the best solution.
When you are making API calls through redux/saga, you can not use async await, as the frameworks will just dispatch an action and return back, the listeners which are registered for the action will be triggered and then after they complete their work they will dispatch a new action and respect reducer will handle the response.
Explained above is general scenario.
In your scenario,
You are dispatching the action returned by getProductReturnAction which will give say GET_PRODUCTS action.
A saga would be registered for GET_PRODUCTS, say getProducts, this get invoked.
This will perform the API call once the response is received it will dispatch GET_PRODUCTS_SUCCESS along with the products data.
Corresponding reducer which handles GET_PRODUCTS_SUCCESS will get called and that updates returnProduct and as you are registered for that in your component the render method gets called (as the props are changed) and hence product data is available in your render method.
This is working perfectly correct. I don't see anything wrong here.
As the data is available in props use the same u do not need to do a setState again on that.

Long polling in Vue.js and Vuex that's independent of components' lifecycle, where to store hot observables for "unsubscribe"?

Problem: Having started multiple long-polling streams that need to persist throughout the app lifecycle (regardless of the lifecycle of individual components), I'm looking for a way to unsubscribe in response to various events (e.g. route change, but not limited to). To that end I wrote the following code:
export const actions: ActionTree<TasksState, RootState> = {
async pollEventTasks({ dispatch, commit, state, rootState }, payload: any) {
const pollEventTasks$ = timer(0, 5000).pipe(
switchMap(_ => tasksService.loadTasksForEvent(payload.eventId)),
map((response: any) => {
commit('setTasks', response);
})
).subscribe();
// this won't work in strict mode. Hot observables ~can't~ shouldn't be written to store:
// commit('longPolling/eventTasksPollingStarted', pollEventTasks$, {root: true});
},
A hot observable "updates itself", thus mutating store outside of mutation handler. What would be a neat solution fitting vue/vuex best practices?
We ended up building a plugin injected via Vue.use and storing Observable subscriptions there

Mutating a state from one module to another Vuex

I'm pretty new to Vuex and am having difficulty understanding how to handle a state change from one module to another. Currently, I have a module called transactions which does an Ajax request and if successful it should close the Modal that is open. I have my modal state set in a separate module called General. I originally tried to set the General State of modal but committing my general mutation closeModal. I realized this won't work and as it sounds like Mutations aren't supposed to do this sort of heavy lifting. I've searched for another method to handle this sort of work and have been lead to Actions but I'm not clear on how to implement it or if it is even supposed to do this kind of work. Would someone please let me know if an Action is the correct method for this problem or if there is another way I should be addressing things.
I have a module called transactions that is running an ajax request and should close a modal if successful. For the sake of this issue, I've simplified my module.
const Transactions = {
state: {
},
mutations: {
CONFIRM_TRANSACTION_CANCEL: function(state) {
this.$store.commit('CLOSE_MODAL')
}
}
And I also have a second module called general which I want to use for general state management and error handling. I'm attempting to call a mutation from transactions into this general module.
const General = {
state: {
modalState: null,
},
mutations: {
...
CLOSE_MODAL: function(state) {
state.modalState = null
},
...
}
}
You should not make a commit inside a mutation. Mutations are only to change the state.
You could do this in two ways:
1.- Using Vue's Watch spying transaction state. Then, if the transaction is correctly done, you dispatch an action to close the Modal.
2.- You can dispatch an action to close the modal inside the action that launches the ajax call (after the success).
apiCall({ dispatch, commit }) {
api.get('/transaction')
.then((response) => {
dispatch('closeModal');
commit('TRANSACTION_SUCCESS', response);
})
.catch((error) => commit('TRANSACTION_ERROR', error));
}
These methods below are done with thinking of the modal as it should use vuex too but, if you want to simplify you can just:
3.- Pass the status of the transaction that comes from vuex directly to the modal by prop and handle the modal with it.

Vuex and Electron carrying state over into new window

I'm currently building an application using Electron which is fantastic so far.
I'm using Vue.js and Vuex to manage the main state of my app, mainly user state (profile and is authenticated etc...)
I'm wondering if it's possible to open a new window, and have the same Vuex state as the main window e.g.
I currently show a login window on app launch if the user is not authenticated which works fine.
function createLoginWindow() {
loginWindow = new BrowserWindow({ width: 600, height: 300, frame: false, show: false });
loginWindow.loadURL(`file://${__dirname}/app/index.html`);
loginWindow.on('closed', () => { loginWindow = null; });
loginWindow.once('ready-to-show', () => {
loginWindow.show();
})
}
User does the login form, if successful then fires this function:
function showMainWindow() {
loginWindow.close(); // Also sets to null in `close` event
mainWindow = new BrowserWindow({width: 1280, height: 1024, show: false});
mainWindow.loadURL(`file://${__dirname}/app/index.html?loadMainView=true`);
mainWindow.once('resize', () => {
mainWindow.show();
})
}
This all works and all, the only problem is, the mainWindow doesn't share the same this.$store as its loginWindow that was .close()'d
Is there any way to pass the Vuex this.$store to my new window so I don't have to cram everything into mainWindow with constantly having to hide it, change its view, plus I want to be able to have other windows (friends list etc) that would rely on the Vuex state.
Hope this isn't too confusing if you need clarification just ask. Thanks.
Although I can potentially see how you may do this I would add the disclaimer that as you are using Vue you shouldn't. Instead I would use vue components to build these seperate views and then you can achieve your goals in an SPA. Components can also be dynamic which would likely help with the issue you have of hiding them in your mainWindow, i.e.
<component v-bind:is="currentView"></component>
Then you would simply set currentView to the component name and it would have full access to your Vuex store, whilst only mounting / showing the view you want.
However as you are looking into it I believe it should be possible to pass the values of the store within loginWindow to mainWindow but it wouldn't be a pure Vue solution.
Rather you create a method within loginWindows Vue instance that outputs a plain Object containing all the key: value states you want to pass. Then you set the loginWindows variable to a global variable within mainWindow, this would allow it to update these values within its store. i.e.
# loginWindow Vue model
window.vuexValuesToPass = this.outputVuexStore()
# mainWindow
var valuesToUpdate = window.opener.vuexValuesToPass
then within mainWindows Vue instance you can set up an action to update the store with all the values you passed it
Giving the fact that you are using electron's BrowserWindow for each interaction, i'd go with ipc channel communication.
This is for the main process
import { ipcMain } from 'electron'
let mainState = null
ipcMain.on('vuex-connect', (event) => {
event.sender.send('vuex-connected', mainState)
})
ipcMain.on('window-closed', (event, state) => {
mainState = state
})
Then, we need to create a plugin for Vuex store. Let's call it ipc. There's some helpful info here
import { ipcRenderer } from 'electron'
import * as types from '../../../store/mutation-types'
export default store => {
ipcRenderer.send('vuex-connect')
ipcRenderer.on('vuex-connected', (event, state) => {
store.commit(types.UPDATE_STATE, state)
})
}
After this, use the store.commit to update the entire store state.
import ipc from './plugins/ipc'
var cloneDeep = require('lodash.clonedeep')
export default new Vuex.Store({
modules,
actions,
plugins: [ipc],
strict: process.env.NODE_ENV !== 'production',
mutations: {
[types.UPDATE_STATE] (state, payload) {
// here we update current store state with the one
// set at window open from main renderer process
this.replaceState(cloneDeep(payload))
}
}
})
Now it remains to send the vuex state when window closing is fired, or any other event you'd like. Put this in renderer process where you have access to store state.
ipcRenderer.send('window-closed', store.state)
Keep in mind that i've not specifically tested the above scenario. It's something i'm using in an application that spawns new BrowserWindow instances and syncs the Vuex store between them.
Regards
GuyC's suggestion on making the app totally single-page makes sense. Try vue-router to manage navigation between routes in your SPA.
And I have a rough solution to do what you want, it saves the effort to import something like vue-router but replacing components in the page by configured routes is always smoother than loading a new page: when open a new window, we have its window object, we can set the shared states to the window's session storage (or some global object), then let vuex in the new window to retrieve it, like created() {if(UIDNotInVuex) tryGetItFromSessionStorage();}. The created is some component's created hook.