How do I set header value from localStorage or Zustand in tRPC and React?
Hello,
This is my tRPC client in my
The problem is if the jwt token changes, it doesn't get changed in the trpcClient unless I do something like this but I don't like it:
What is the best way to set jwt to trpc client?
This is my tRPC client in my
App.tsxApp.tsx:function App(): JSX.Element {
const { token } = useAuthStore()
const [trpcClient] = useState(() =>
trpcReact.createClient({
links: [
httpBatchLink({
url: 'http://192.168.1.17:3000/trpc',
fetch(url, options) {
return fetch(url, {
...options,
credentials: 'include'
})
},
headers: () => {
return {
Authorization: `Bearer ${token || ''}`
}
}
})
],
transformer: SuperJSON
})
)function App(): JSX.Element {
const { token } = useAuthStore()
const [trpcClient] = useState(() =>
trpcReact.createClient({
links: [
httpBatchLink({
url: 'http://192.168.1.17:3000/trpc',
fetch(url, options) {
return fetch(url, {
...options,
credentials: 'include'
})
},
headers: () => {
return {
Authorization: `Bearer ${token || ''}`
}
}
})
],
transformer: SuperJSON
})
)The problem is if the jwt token changes, it doesn't get changed in the trpcClient unless I do something like this but I don't like it:
useEffect(() => {
if (token)
setTRPCClientZS(
trpcReactZS.createClient({
links: [
httpBatchLink({
url: 'http://192.168.1.17:3000/trpc',
fetch(url, options) {
return fetch(url, {
...options,
credentials: 'include'
})
},
headers: {
Authorization: `Bearer ${token}`
}
})
],
transformer: SuperJSON
})
)
}, [token])useEffect(() => {
if (token)
setTRPCClientZS(
trpcReactZS.createClient({
links: [
httpBatchLink({
url: 'http://192.168.1.17:3000/trpc',
fetch(url, options) {
return fetch(url, {
...options,
credentials: 'include'
})
},
headers: {
Authorization: `Bearer ${token}`
}
})
],
transformer: SuperJSON
})
)
}, [token])What is the best way to set jwt to trpc client?