store
store copied to clipboard
Usage question.
I have one question - how to filter the data from the store ? Example - I have stored the todos list and I want to find/filter the todo which has specific attribute ID = xr34dfg . How do we achieve such scenario?
Hi,
If you are using @select
or .select
- it's returning an Observable, to filter a list of todos for example, could have something like:
@select(['todos']) todos$;
filteredTodos$ = this.todos$.map(todos=>todos.filter(todo=>todo.id==='xr34dfg')
If the filter value (ie: xr34dfg) is something that is stored in the store also - and you want to filter based off of something in the store, could do something like
@select(['todos']) todos$;
@select(['filterValue']) filterValue$;
filteredTodos$ = this.todos$.combineWithLatest(this.filterValue,(todos,filter)=>{
return todos.filter(todo=>todo.id===filter)
})
Then any time the active filter changes, or the list changes - the filtered list will get the new value
In my case I am using reselect, which is easier for us in larger projects - it keeps the components small and the selectors are reusable. I use it like this (I try to do the same example as above):
// in the todo selectors
const getTodos = (state) => state.todos;
const getTodoById = createSelector(
getTodos,
(state, secondParam) => secondParam,
(todos, id) => (
todos.find(todo => todo.id === id)
),
);
...
// in the component
@select(state => getTodoById(state, 'xr34dfg')) myTodo$;
...
or if it is stored in the store
// in the todo selectors
const getTodos = (state) => state.todos;
const getStoredTodo = (state) => state.filterValue;
const getTodoById = createSelector(
getTodos,
(state, secondParam) => secondParam,
(todos, id) => (
todos.find(todo => todo.id === id)
),
);
const getTodoByStoredValue = createSelector(
getTodos,
getStoredTodo,
(todos, storedTodo) => getTodoById(todos, storedTodo),
);
...
// in the component
@select(getTodoByStoredValue) myTodo$;
...