How to pass state to form actions #10506
-
Use case
Scenario 1Fetch the user profile in // +hooks.server.ts
export const handle: Handle = async ({ event, resolve }) => {
const user = await fetchUserProfile()
const postApi = createPostApi()
event.locals = {
user,
postApi
}
}
// routes/post/create/+page.server.ts
export const actions = {
default: async ({ request, locals: { user, postApi } }) => {
const data = await request.formData()
const { workspace_id } = user
await postApi.create({
...data,
workspace_id
})
}
} Scenario 2Fetch the user profile in // +layout.server.ts
export const load = async () => {
const user = await fetchUserProfile()
return {
user
}
}
// routes/+layout.svelte
<script lang="ts">
import { setContext } from 'svelte'
import { writable } from 'svelte/store'
import type { LayoutData } from './$types'
const workspaceId = writable('')
export let data: LayoutData
$: workspaceId.set(data.user.workspace_id)
setContext('workspaceId', workspaceId)
</script>
// routes/post/create/+page.svelte
<script lang="ts">
import { getContext } from 'svelte'
const workspaceId = getContext('workspace')
</script> Given that shared stores can't be used with SSR, how can I fetch important user data when the app load for the first time, keep this information in the app state and update the database in a form action with the user context. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Just pass the data to the action with a form and <input type="hidden" /> |
Beta Was this translation helpful? Give feedback.
Just pass the data to the action with a form and