How to pass parameters to a derived store? #8325
-
I'm porting a Vue 2 application to SvelteKit 1.0.0, but I'm having a bit of trouble with derived stores. This is an excerpt from the user store in the Vue 2 app: const getters = {
isAdmin: (state) => userLevel(state.userLevel) === userLevels.admin,
authorizationHeader: (state) => (state.jwtToken ? { Authorization: `Bearer ${ state.jwtToken }` } : {}),
can: (state) => (action, target) => {
const requiredUserLevel = requiredUserLevels[target][action]
if (requiredUserLevel === undefined) {
console.error(`Invalid permissions check for ${ target }/${ action }`)
return false
}
return (userLevel(state.userLevel) >= requiredUserLevel)
},
} I've managed to get everything working, except for export const isAdmin = derived(user, ($user) => ($user.userLevel === UserLevel.Admin))
export const authorizationHeader = derived(user, ($user) => ($user.jwtToken ? {
Authorization: `Bearer ${$user.jwtToken}`,
} : {}))
export const can = derived(user, ($user) => (action: keyof PageAction, target: keyof UserLevelRequirement) => {
const requiredUserLevel = requiredUserLevels[target][action]
if (requiredUserLevel === undefined) {
console.error(`Invalid permissions check for ${target}/${action}`)
return false
}
return ($user.userLevel >= requiredUserLevel)
}) Putting
Is there a way of passing parameters to a derived store, or having it return a function that I can call? The docs are very light on the subject, to say the least… (also, is there a way of putting SvelteKit into a developer mode where the full stack trace gets shown in the browser, rather than just "500 Internal Error"? It would speed things up when using tiny laptop screens…) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Something like this. Not sure currying is a good practice, docs say use derived with multiple stores. <script lang="ts">
import { readable, derived } from 'svelte/store';
const requiredUserLevels: Record<string, Record<string, number> | undefined | undefined> = {
view: {
page: 999,
},
};
const user = readable({ name: 'admin', userLevel: 999 });
const can = derived(user, ($user) => (v: string, p: string) => {
const requiredLevel = requiredUserLevels[v]?.[p];
if (!requiredLevel) return false;
return $user.userLevel >= requiredLevel;
});
</script>
<p>
{$can('view', 'page')}
{$can('edit', 'page')}
{$can('view', 'dashboard')}
{$can('edit', 'dashboard')}
</p>
|
Beta Was this translation helpful? Give feedback.
Something like this. Not sure currying is a good practice, docs say use derived with multiple stores.