N
Nuxt6mo ago
MrDeer

How to use useState with functions inside

Hey, I have been trying to create a composable for a header, which contains all details about the header. The issue I am facing is, that the useState composable cannot hold functions, otherwise I will get a cannot stringify a function during SSR. What is the recommended workaround to a composable like this?
interface Header {
title?: string
back?: boolean
secondary?: {
icon: string
to?: string
click?: () => void
}
transparent?: boolean
}
export default function () {
const state = useState<Header>('header', () => ({}))
const setHeader = (header: Header) => {
state.value = header
}

return { setHeader, header: readonly(state) }
}
interface Header {
title?: string
back?: boolean
secondary?: {
icon: string
to?: string
click?: () => void
}
transparent?: boolean
}
export default function () {
const state = useState<Header>('header', () => ({}))
const setHeader = (header: Header) => {
state.value = header
}

return { setHeader, header: readonly(state) }
}
5 Replies
handshake
handshake6mo ago
idk where you're storing the composable but is it structured like this? https://github.com/snolan-ethika/nuxt-stuff/commit/96b0bc24e68c00b9bac4e11402c3b5c19668a348
MrDeer
MrDeerOP6mo ago
of course, try setting click to function and render it on ssr. it will fail, because useState cant hold functions in state
handshake
handshake6mo ago
do you mean like this?
No description
No description
MrDeer
MrDeerOP6mo ago
Like this for example:
setHeader({
secondary: {
click: () => navigateTo('/');
}
})
setHeader({
secondary: {
click: () => navigateTo('/');
}
})
handshake
handshake6mo ago
is that a nuxt thing?
Want results from more Discord servers?
Add your server