Search code examples
reactjstypescriptasynchronoushref

How to change window.location.href according to return value?


I use this in render function

    @observable private redirectUrl: string = null;

    public async componentWillMount() {
        this.redirectUrl = await this.getRedirectUrl();
    }

    public render() {
        if (this.redirectUrl) {
            window.location.href = this.redirectUrl;
            return null;
    } 



where redirectUrl is observable and get by a async function. But it is not working in componentWillMount function. I think the reason is that it is get by async.

How to solve this?


Solution

  • As async function will return a promise, you can do something like following,

    async componentWillMount () {
        await anotherAsyncFunction()
        window.location.href = this.redirectUrl
    }
    

    Hope will work.