store icon indicating copy to clipboard operation
store copied to clipboard

Usage question.

Open PaulD1980 opened this issue 7 years ago • 2 comments

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?

PaulD1980 avatar Sep 02 '17 02:09 PaulD1980

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

e-schultz avatar Sep 07 '17 12:09 e-schultz

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$;
...

JPeer264 avatar Sep 12 '17 11:09 JPeer264