简体   繁体   中英

How do I filter a store list in sveltekit?

Trying to return messages that match parentId = id .

I'm not sure how to pass an argument to the function:

export const getReplies = derived([id], ([$messages, $id]) => {
    return $messages.filter(msg => {
        return msg.parentId === $id;
    });
});

component:

$: replies = getReplies(msg.id);

You could create a function that returns a derived store

function getReplies(id) {
 return derived(
   messages, 
   $messages => $messages.filter(msg => msg.parentId == id)
 )
}

and you use it the same:

$: replies = getReplies(msg.id)

Now replies is a store (so you access it with $replies) and it will update everytime either messages (the original store) changes, or if msg.id changes (at that moment a new derived store will be generated for you.

The derived function returns a store .
If your messages are a store and the id is a store , you can derive from both, like this:

const replies = derived([messages, id], ([$messages, $id]) => {
  return $messages.filter(msg => {
    return msg.parentId === $id;
  });
})

Working example: https://svelte.dev/repl/d3553520239a49dc8a0bc8b147b14cf2?version=3.46.4


Or you don't need to use derived at all, like:

$: replies = $messages.filter(msg => {
        return msg.parentId === id;
  });

Working example: https://svelte.dev/repl/ab500b1bd0914172b7b409e044b5fa01?version=3.46.4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM