Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If item not in the store, dispatch an action to fetch it

Tags:

angular

ngrx

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]
   }
})
like image 646
doron Avatar asked Aug 02 '17 19:08

doron


People also ask

How to dispatch an action from a React component?

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.

How do you trigger a state change in dispatch?

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.

What is a dispatch in flux and why is it forbidden?

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.

How to dispatch multiple actions in a single method in JavaScript?

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.


1 Answers

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.

like image 162
daddykom Avatar answered Oct 03 '22 20:10

daddykom