如何确保在挂载组件之前有数据?

时间:2018-10-23 10:14:10

标签: reactjs graphql react-apollo prisma

用户单击链接,客户端从URL读取令牌。然后将令牌传递到signup突变。在后端,我已将该令牌保存到用户,因此我可以查询并找到该用户。问题是我在客户端GraphQL error: No user found上遇到错误。我假设令牌没有传递给突变signup(shortLivedToken: String),这就是为什么我无法在后端查询用户的原因。在graphql操场上,一切正常。我知道我从url获得令牌,因为它位于props.match.params.token中,这是我的前端SignUp组件:

class SignUp extends Component {
  constructor(props) {
    super(props)
    this.state = { shortLivedToken: props.match.params.token }
  }

  handleMutation = async mutation => {
    try {
      const res = await mutation()
      console.log(res)
    } catch (e) {
      console.log(e)
    }
    // const token = res.data.signUp.token
    // localStorage.setItem(AUTH_TOKEN, token)
    // this.setState({ error: e.message })
    // }
  }

  render() {
    return (
      <Mutation
        mutation={SIGN_UP}
        variables={{ shortLivedToken: this.state.shortLivedToken }}
      >
        {(mutation, { data, loading, error }) => {
          if (loading)
            return (
              <Pane
                display="flex"
                alignItems="center"
                // justifyContent="center"
                height={400}
              >
                <Spinner />
              </Pane>
            )
          if (error)
            return (
              <Pane
                display="flex"
                alignItems="center"
                justifyContent="center"
                height={400}
              >
                <p>{this.props.match.params.token}</p>
                <Text>Error occurred {error.message}</Text>
              </Pane>
            )
          this.handleMutation(mutation)
          return null
        }}
      </Mutation>
    )
  }
}

1 个答案:

答案 0 :(得分:0)

不应从渲染调用handleMutation,您可以在react-apollo中使用graphql HOC并获得props中的突变,并在react lifecycle方法中使用它来获取数据。

graphql(SIGN_UP, {
  name: 'signUp'
})(SignUp)

componentDidMount () {
  this.props.signUp({
    variables: {
      shortLivedToken: this.props.match.params.token
    }
  })
}

您的handleMutation函数应如下所述:

handleMutation = async mutation => {
try {
  const res = await mutation({variables: this.props.match.params.token})
  console.log(res)
} catch (e) {
  console.log(e)
}
// const token = res.data.signUp.token
// localStorage.setItem(AUTH_TOKEN, token)
// this.setState({ error: e.message })
// }

}

,您也可以从componentDidMount调用此函数。

希望这会有所帮助

相关问题