localStorage.getItem()在graphql查询之前响应返回undefined

时间:2018-03-19 19:58:11

标签: javascript reactjs graphql auth0

使用 graphql,react和auth0

用户从auth0登录时,该标记会添加到localStorage.setItem('user_email', authResponse.email)

然后他们转到主页面,我有这个graphql查询:

 export default graphql(USER_QUERY, {
       name: 'userQuery',
       skip: () => (localStorage.getItem('user_email') === null ||
                    localStorage.getItem('user_email') === 'undefined'),
       options: ()=>{
          return { variables: {email: localStorage.getItem('user_email')}}
       })(Component)

问题是,查询永远不会执行,因为getItem()太晚返回电子邮件。相反,我收到它尝试发送undefined的错误。

我如何等待localStorage? promise之后可以解决吗?我应该以某种方式使用componentDidMount(){}吗?

我尝试但获取this.props.userQuery.refetch()失败了,我将setTimeout()使用新变量重新获取,但我无法正确编写或让它工作。

编辑以下是用于设置会话的Auth.js文件:

setSession(authResult) {
    //return new Promise((resolve, reject)=> {
    // Set the time that the access token will expire at
    let expiresAt = JSON.stringify(
        authResult.expiresIn * 1000 + new Date().getTime()
    );
    localStorage.setItem('access_token', authResult.accessToken);
    localStorage.setItem('id_token', authResult.idToken);
    localStorage.setItem('expires_at', expiresAt);
    localStorage.setItem('user_email', authResult.idTokenPayload.email)

    history.replace('/dashboard/home')
}

1 个答案:

答案 0 :(得分:0)

我发现有一些资源说你不能用graphql查询进行异步调用,所以总是会跳过它。相反,我在componentDidMount()上调用了查询,如下所示:

componentDidMount(){
        const checkEmailAndQuery = () => {
            if(this.state.userId === null) {
                if (localStorage.getItem('user_email') !== null) {
                    this.props.client.query({
                        query: USER_QUERY,
                        variables: {email: localStorage.getItem('user_email')}
                    }).then(({data}) => {
                        this.setState({userId: data.user.id})
                    })
                } else {
                    setTimeout(checkEmailAndQuery, 200)
                }
            }
        }
        checkEmailAndQuery()
    }