0

I have the following code in Login component:

function auth(opts){
  return axios(opts).then(response => response.data)
}
auth(opts).then(data=> isLogged.set('assets'))

Main app:

$: currComponent = isLogged=='assets' ? Assets : null

<Login />
<svelte:component this={currComponent} />

By some reason Svelte doesn't wait until the promise get resolved.

However if I move isLogged.set('assets') outside of promise:

Api.auth(opts).then(data=> console.log(data))

isLogged.set('assets')

result of promise returned and component get mounted. What I'm doing wrong?

1 Answer 1

1

Svelte will not wait the end of your promise to work and be mounted. It's good to note that Svelte doesn't detect a change on a variable when you are using a function or a method. You have to reassign them. So if we try to reproduce your code and fix it:

<script>

    import Login from './Login.svelte';
    import Assets from './Assets.svelte';

    let isLogged;

    $: currComponent = isLogged == 'assets' ? Assets : null;

    Api.auth(opts).then(data=> {
        isLogged = 'assets';
    })

</script>

<Login />
<svelte:component this={currComponent} />

Another option would be to use await block

Sign up to request clarification or add additional context in comments.

7 Comments

As I understand - the only difference is that auth is called in App, no Login component. But if I'm using store in Login to pass isLogged to App (isLogged.set(..), why it isn't working?
Svelte requires a reassignment to be reactive. When you asssign a variable using a method or a function, you don't reassign the variable, so it will not work.
But whats about promise resolving? it need to wrap the call into a function. But inside it the code seems don't work.
I meant that Svelte doesn't wait result of request if it was called inside a function: function(){ Api.auth(opts).then(data=> { isLogged = 'assets'; }) })()
The other option that you can use is the await block
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.