Search code examples
angularngrxngxs

Select value from state in NGXS by passing it a parameter


I have a state which contains JSON as below:

{id: "1", name: "ig1", description: "ig 11"}
{id: "5", name: "hhh", description: "hhh"}
{id: "6", name: "ggg", description: "hhh"}

I need to select data for id = 1 from the state array

How can this be done using NGXS state selector

And how can we access it in component?


I have below content in state

recipes

0 : {id: "3", name: "Cake", image: "index.jpg", description: "Lorem Ipsum is 
simply dummy text of the printing a…ldus PageMaker including versions of 
Lorem Ipsum.", ingredients: "ig 1-1kg,ig 123-4kg"}
1 : {id: "16", name: "gfdg", image: "Chrysanthemum.jpg", description: 
"fhfgh", 
ingredients: "gdfg-4sfhs,ig 1-1kg"}
2 : {id: "17", name: "hfgh", image: "Jellyfish.jpg", description: "ghgfh", 
ingredients: "ig 123-5kg,ig 1-3kg"}
3 :{id: "18", name: "hgj", image: "Koala.jpg", description: "ghjhgj", 
 ingredients: "gdfg-5sfhs"}

I want to get data in state for index 1, i.e. {id: "16", name: "gfdg", image: "Chrysanthemum.jpg", description: "fhfgh", ingredients: "gdfg-4sfhs,ig 1-1kg"}

As per your reply I have added below code

In component:

import { RecipeState } from '../../state/recipe.state';
edit_details :  Observable<string[]>;

editRecipepopup( id ) {
this.edit_details = this.store.select(RecipeState.findById).pipe(map(filterFn 
=> filterFn(id)));
console.log("edit=>",this.edit_details);
}

In state:

@Selector()
static findById(state: string[]) {
return (id: string) => { //<--- Return a function from select
    console.log("id=>"+id);
   return state.filter(s => s.indexOf(id) > -1);
};
}

But I do not get the data. Also my id is not logged in console


Solution

  • Here you go , this is how you can query your state :

    In your State file :

    @Selector() 
    static getIndexed(state: any[]) {
        return (index: number) => { //<--- Return a function from select
            return state[index];
        };
    }
    

    From Your Component :

    this.store.select(YourState.getIndexed).pipe(map(filterFn => filterFn(YOUR_INDEX))); 
    

    WORKING DEMO ( And For More Detail : Do Read )