I'm trying to make a function in svelte and urql to get the user logged only if it's already setted in the store. Otherwise i get it from the api.
In my login submit form i set in the store the user value :
function onSubmit() {
if ($data?.user) {
userLogged.update((s) => ({
...s,
user: $data?.user,
}));
}
});
and in another component here i try to get the value from store if exist or from api :
<script lang="ts">
let user: any;
const getUser = () => {
let user = get(userLogged);
if (user.user !== null) {
return user;
} else {
const userQuery = queryStore({
client: getContextClient(),
query: USER_QUERY,
});
userQuery.subscribe((val) => {
console.log("val ?", val?.data?.user);
userLogged.update((s) => ({ ...s, user: val?.data?.user }));
user = val?.data?.user;
});
return user;
}
};
user = getUser();
console.log("user", user);
</script>
But when i refresh the page at the first rendering the console.log return undefined and then when the component is updated it return the user correctly. I don't understand why because the console.log into the subscribe return the good value everytime and i assign it to the user variable
Finally it worked. I just set my store value in a parent component and imported it it the different children, and then the value is correctly get back in the first rendering.