【问题标题】:localStorage.getItem() react returning undefined before graphql querylocalStorage.getItem() 在 graphql 查询之前反应返回 undefined
【发布时间】:2018-08-28 12:15:38
【问题描述】:

使用 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')
}

【问题讨论】:

  • 你能把登录调用和跳转到主页的代码贴出来吗?
  • 我不知道为什么你有localStorage.getItem('user_email') === 'undefined' 条件,你真的期待'undefined' 字符串还是应该是localStorage.getItem('user_email') === undefined?此外,如果您只使用localStorage.setItem()localStorage.removeItem(),它应该是null 或您设置的字符串值。
  • @AdamPatterson 我刚刚添加了它,未定义的部分是为了确保它不会尝试使用未定义的结果进行查询,因为如果没有,则不会发生查询,因为它只是被完全跳过。
  • @KevinDanikowski 虽然就像 tudorpavel 说的,它应该是 NULL。 Localstorage 返回NULL,不是未定义的。

标签: javascript reactjs graphql auth0


【解决方案1】:

我发现一些资源说您不能使用 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()
    }

【讨论】:

    猜你喜欢
    • 2018-10-08
    • 2018-03-08
    • 2022-12-29
    • 1970-01-01
    • 2019-06-14
    • 2020-01-07
    • 2018-10-26
    • 2018-11-24
    • 1970-01-01
    相关资源
    最近更新 更多