I'm trying to figure out what is the best way to fetch an item if it's not in the store.
For instance, let say that I have a list of users and I want to fetch a specific user. If that user isn't in the store I want to fetch him from the DB.
Is this code below considered best practice or is there a better way doing so?
const searchedUserId = 'abcdefg';
this.selecedUser$ = this.store.select(state => {
const selectedUserIndex = state.userList.findIndex(searchedUserId)
if (selectedUserIndex === -1) {
this.store.dispatch(new UsersActions.FetchUsers(searchedUserId));
} else {
return state.userList[selectedUserIndex]
}
})
When we want to dispatch an action from our React component, we need to first connect it with the store and use the "connect" method of react-redux, i.e., the second approach discussed above. When we start having logic in our mapDispatchToProps function, we can dispatch action in our saga, i.e., the third approach, which we discussed in detail.
dispatch(action) 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.
In Flux, a dispatch is forbidden while Stores are handling the action and emitting updates. This is unfortunate because it makes it impossible to dispatch actions from component lifecycle hooks or other benign places.
If we want to dispatch many actions in a single method, we can do that as shown below: To run many async instructions one after the other and also maintain readability of the code, we can dispatch an action that will then trigger a saga.
const searchedUserId = 'abcdefg';
this.selecedUser$ = this.store.select('userList').pipe(
map(userList=>{const result = userList.findIndex(item=>item.id===searchedUserId);
return result === -1 ? {} : result;
}),
tap(userList=>{
if( !userList.hasOwnProperty('id') ) this.store.dispatch(new UsersActions.FetchUsers(searchedUserId));
})
);
tap will not change the observable and when the dispatched action will change the state, the observable will be updated.
Use an selector instead of the select statement and be aware about the situation the action will not found the key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With