Reacting to a store change outside the context of a root or render function

I have a user store to manage user token etc. global-store.ts
export const [userStore, setUserStore] = makePersisted(
createStore<UserStoreState>({
user: null,
tokens: null,
accessToken: '',
}),
{ name: 'linkerly-user-store', storageOptions: { type: 'localStorage' } },
);
export const [userStore, setUserStore] = makePersisted(
createStore<UserStoreState>({
user: null,
tokens: null,
accessToken: '',
}),
{ name: 'linkerly-user-store', storageOptions: { type: 'localStorage' } },
);
I'm also experimenting with the library called wretch. linkerly-api.ts
const getAccessToken = () => {
return userStore.accessToken;
};

export const linkerlyApi = wretch(API_URI)
.headers({ 'Content-Type': 'application/json' })
.auth(`Bearer ${getAccessToken() ?? 'no'}`)
const getAccessToken = () => {
return userStore.accessToken;
};

export const linkerlyApi = wretch(API_URI)
.headers({ 'Content-Type': 'application/json' })
.auth(`Bearer ${getAccessToken() ?? 'no'}`)
After a successful login I am setting the user store.
setUserStore(
produce((draft) => {
draft.user = loginResponse.user;
draft.tokens = loginResponse.tokens;
draft.accessToken = loginResponse.tokens.accessToken;
}),
);
setUserStore(
produce((draft) => {
draft.user = loginResponse.user;
draft.tokens = loginResponse.tokens;
draft.accessToken = loginResponse.tokens.accessToken;
}),
);
The question is if I don't wrap the
userStore.accessToken
userStore.accessToken
in a createEffect it's not reactive and auth token doesn't get injected into the http client. If I wrap it I am getting 'computations created outside a createRoot or render will never be disposed'. Felt like I am doing something that's not supposed to do or recomennded and there should be a better way to do all of these. Any idea?
1 Reply
bigmistqke
bigmistqke4mo ago
Since components only run once you will need effects to react on signal changes. U can think of JSX as being an effect too, so any signal accessed in JSX will be reactive too. Is the effect outside a component? If yes, you could look at createRoot. The warning is about the fact that when u use effects inside components it will automatically dispose when the component gets unmounted, if u use effects outside components u will have to manage that yourself.