My use case comprises of dispatching two actions from a recursive function (if else construct ) the if part which adds a row in an array ( which is a state of my app) and the else part adds another row and needs to access the length of the array before and call the function itself. What I see here is the length of the array remains same after the first action is being dispatched and thus the call to itself doesn't get the actual value of the length .
My assumption is you are trying to do the second check/call after the first within the component. The component must wait for the new props on the next render. You should move your logic into your action. This is just a guess without more details to the question. Here is an example:
const myAction = (stuff) => {
return (dispatch, getState) => {
let oldLength = getState().myState.stuff.length
dispatch(doStuffToStuff(stuff))
let newLength = getState().myState.stuff.length
dispatch(moreStuffToLength(newLength))
}
}
Thanks the issue was resolved .After every dispatch if the state changes it is required to access the new state by ysing getState() I wasn't doing that .
Related
I'm using ngrx/component-store and loving it so far. Having prior store knowledge building my own simple ones, the only real headache I've had so far is when I've had to update an array and figured out I have to always create a new one for the internal compare() pipe to realize the array got updated.
Anyway, reading through the documentation it talks about updater methods and patchState. To me they do exactly the same thing, but their creation is slightly different. You would call patchState inside of a method while this.updater() returns a method giving you a function you can expose in your service. Anytime I'm updating my state it's always after a network call. I assume there are plenty of scenarios where you'd want to update your state without a network call so this is why you would want to have an updater available to your component to call. The question is if an updater and patchState are really doing the same thing then is it a better practice to call an updater in an effect or use patchState, or maybe am I putting too much logic in my effect?
On a side note, the docs say an updater method is supposed to be a pure function. If you're using it to your push an object onto an array then is it really pure?
// adding the selectors so people know what components are subscribing to
readonly approvals$ = this.select(state => state.requestApprovals);
readonly registration$ = this.select(state => state);
readonly updateAssessment = this.effect(($judgement: Observable<{id: string, isApproved: boolean}>) => {
return $judgement.pipe(
switchMap((evaluation) => {
const state = this.get();
return this.requestApproval.patch(state.id, state.companyName, evaluation.id, evaluation.isApproved).pipe(
tapResponse(
(result) => {
// is it better to call patchState()?
this.patchState((state) => {
for(let i = 0; i < state.requestApprovals.length; i++) {
if(state.requestApprovals[i].id == result.id) {
state.requestApprovals[i].isApproved = result.isApproved;
}
}
// the take away is you must assign a whole new array object when you update it.
state.requestApprovals = Object.assign([], state.requestApprovals);
return state;
});
// or this updater?
// this.applyDecisionPatch(evaluation);
},
// oh look! another updater reassigning my array to the state so
// it propagates to subscribers to reset the UI
() => { this.reverseDecision(); }
)
);
})
);
});
// this is private to make sure this can only be called after a network request
private readonly applyDecisionPatch = this.updater((state, value: {id: string, isApproved: boolean}) => {
for(let i = 0; i < state.requestApprovals.length; i++) {
if(state.requestApprovals[i].id == value.id) {
state.requestApprovals[i].isApproved = value.isApproved;
}
}
state.requestApprovals = Object.assign([], state.requestApprovals);
return state;
});
Note: There's no tag for ngrx-component-store so couldn't tag it.
An updater can be compared to a reducer.
All the options to modify the state should change it in an immutable way.
A library like ngrx-immer can be used to make this easier.
The main difference is that updater receives the current state, and you can change the state based on it. E.g. a conditional update, or can be used with #ngrx/entity
While with setState and patchState, you just set state properties.
setState updates the whole state object, whereas patchState only sets the given properties and doesn't touch the rest of the state object.
These two methods are also easier to use when you just want to set the state, because you don't have to create an updater function.
To answer the side question, push is not immutable. Instead of creating a new instance, it updates the array instance.
As a scenario, the user can click a button to create a list of timestamps that shows the corresponding times when the clicks are made. User can also click on an item on the list to remove an item.
In terms of the store, there's a counter state that keeps track of how many times the button has been clicked, and then there's another state that keeps track of a list of timestamps. And each item on list state has an id field that derive from the counter state. So one part of the store depends on another part.
As an attempt, I dispatch one action, and both reducers handle the same action, and it works fine, but only that it's not DRY. Before dispatching, I have to add 1 to the counter state in order to get the new id which I use as the action payload, after dispatching, I add 1 to the counter state again to return the new counter state. That's repeating myself.
What's the general standard way of handling a problem of this nature?
The general simple way is to use thunks. You need to setup a middleware, check out the docs:
https://github.com/gaearon/redux-thunk
This allows you to dispatch a function instead of a simple action. Within that function, you can access state and dispatch as many times as you want.
In your scenario, you would first increment the counter, then retrieve the length to get your new id, and then dispatch another action to create a timestamp.
Some imaginary code for your action creators:
// basic action creators to be handled in your reducers
function incrementCounter(){
return { type: 'INCREMENT'}
}
function createTimestamp(id){
return { type: 'CREATE_TS', id }
}
// this is the thunk
function incrementAndTimestamp(){
return (dispatch, getState) => {
// increment the counter
dispatch(incrementCounter())
// generate an "id" from the resulting state
const newId = getState().counter.length
// and use that id to further update your state
dispatch(createTimestamp(newId))
}
}
You will need to handle those 2 different actions in your reducers and you have now two separate pieces of code. The thunk is the glue that dispatches, gets the data from one part, and uses it to affect the other part.
I want to load all the items on start without showing any message, but once after loaded. I want to capture any new row in subscriber and show it to the desktop notification.
The problem is, I'm not sure how to check if all the previous items are loaded and if the row is new item or is it from previous existing item.
this.items = this.af.database.list('notifications/'+this.uid+'/');
this.items.subscribe(list => {
list.forEach(row => {
// doing something here...
});
// once all the rows are finished loading, then any new row, show desktop notification message
});
I have user lodash for the minimal code.
// this varible holds the initial loaded keys
let loadedKeys = [];
this.items = this.af.database.list('notifications/'+this.uid+'/');
this.items.subscribe((list)=>{
// we skip it while initial load
if(!_.isEmpty(loadedKeys)){
// different is the new keys
let newKeys = _.difference(_.map(list, "$key"), loadedKeys);
if(!_.isEmpty(newKeys)){
// ... notification code here
}
}
loadedKeys = _.map(list, "$key");
});
The behave you are looking for is the default Subject approach in RxJS.
Check this reactiveX url to follow the marble diagram of Publish Subject (the equivalent for Subject in RxJS).
So you have two easy options:
1) manually index witch rows you want to display like #bash replied
2) create a Rx.Subject() and assign only the newest's rows to it. Then you subscribe to this subject in your app workflow.
The advantage of method 2 is when a new .subscribe occur, it will not retrieve previous data.
Edit: I wrote this codepen as a guide to implement your custom RxJS Subject. Hope it helps.
Assuming your rows have something unique to match with previous rows you can do the following:
// A Row item has a unique identifier id
interface Row {
id: number;
}
this.rows: Row[];
this.items$ = this.af.database.list(`notifications/${this.uid}/`).pipe(
tap(list => {
// if rows is not array, first time...
if(!Array.isArray(this.rows)) {
// first time nothing to do
return;
}
// returns true if some item from list is not found in this.rows
const foundNewRow = list.some(item => {
return ! this.rows.find(row => row.id === item.id);
});
if (foundNewRow) {
// call method to show desktop message here
}
}
);
I used a pipe and a tap operator (that you will have to import). If you subscribe to this.items$ the tap operator will do the work:
this.items$.subscribe((items => this.rows = items));
If you do not want to set this.rows when normally subscribing than you can also do this in the tap operator. But that would assume you only use it for checking difference between existing and new items.
I have a Redux app that is displaying a list of Properties based on a set of Filters (user input).
Quick description of my state:
filters – Filters values object...
properties – Repo of all properties available on page
visibleProperties – List of properties with current filters applied
The problem is when I dispatch & set a new filter value, I need to filter properties based on filters new state and to store the result in visibleProperties.
So I came up with this solution:
export function setBedroomFilter (value) {
return (dispatch, getState) => {
// 'SET_FILTER' action
dispatch(setFilter('bedroom', parseInt(value)))
// New state
const { filters, properties } = getState()
// 'FILTER_PROPERTIES' action (Depending on new state)
dispatch(filterProperties(properties, filters))
}
}
And visibleProperties reducer can do its work:
// case 'FILTER_PROPERTIES'...
visibleProperties = action.properties.filter(item => item.bedroom >= action.filters.bedroom)
Is this approach totally fine?
From the documentation of dispatch:
Dispatches an action. This is the only way to trigger a state change.
The store's reducing function will be called with the current
getState() result and the given action synchronously. Its return value
will be considered the next state. It will be returned from getState()
from now on, and the change listeners will immediately be notified.
It's a synchronous function and it's totally fine to use in the way you've described(as long as setFilter is synchronous). However, if you're doing asynchronous operation in setFilter,(assuming that Promise returned from setFilter) you should chain your dispatch calls like this:
dispatch(setFilter('bedroom', parseInt(value))).then(() => {
// New state
const { filters, properties } = getState()
// 'FILTER_PROPERTIES' action (Depending on new state)
dispatch(filterProperties(properties, filters))
}
Another option might be using selectors. Please check it out:
https://github.com/reactjs/reselect
I have this question in my head, not sure if this is validate or not, below it's an example of redux middle console log out the store.
const logger = store => next => action => {
console.log('dispatching', action)
let result = next(action)
console.log('next state', store.getState())
return result
}
I can see it's using currying, so in redux is calling as logger(store)(store.dispatch)(action) (Correct me if i am wrong). My question is why we currying here instead just
(store, next, action) => { // do the rest }
Thanks for any suggestion I am slowly moving into functional programming too to get my head up rhythm with it.
I think redux wants to provide three hooks to developers.
We can split the call chain logger(store)(next)(action) into
let haveStoreAndDispatch = logger(store);
let haveNext = haveStoreAndDispatch(next);
let haveAction = haveNext(action);
Then we get three hook functions.
In haveStoreAndDispatch callback function, store have been created.
In haveNext callback function, we have get the next middleware.
In HaveAction callback function, we can do something with the previous middleware's result action.
Callbacks haveStoreAndDispatch and haveNext just be called only once in applyMiddleware(...middlewares)(createStore).