1

I am passing an access token into a functional component as props. I need the functional component to re-render when the access token has change. I am using useEffect to setState when said access token has change. It is not re-rendering as expected.

const Panel = (props) => {

  const [accessToken, setAccessToken] = useState('');

  useEffect(() => {
    setAccessToken(props.accessToken)
  }, [props.accessToken])

  return (...)
}

Expected: Panel re-render after props.accessToken changes.

Actual: Panel does not re-render with updated props.accessToken value.

8
  • Everything looks good with your code. Can you provide a reproducible example Commented Sep 4, 2019 at 1:01
  • 1
    Have you verified that a defined value for accessToken is passed to Panel? ie, a value that is not '' as per the inital state? Commented Sep 4, 2019 at 1:07
  • @DacreDenny How would I verify that in Panel? I tried console log in the useEffect and it returns null for accessToken. accessToken value is defined in the parent component by an api call which sets the token value with "this.accessToken = response.data". Then, <Panel accessToken={this.accessToken} /> Commented Sep 4, 2019 at 1:13
  • If you add console.log("props.accessToken=", props.accessToken) before the line with useState, what is logged? Commented Sep 4, 2019 at 1:15
  • 1
    I cannot post source code due to company policy. However, in the parent component instead of setting access token value to this.accessToken, I set the access token value to state. That seems to solve the problem. So does this mean component variable changes is not passed down to child component unless it is a state variable? Commented Sep 4, 2019 at 1:31

1 Answer 1

3

As per your comment,

accessToken value is defined in the parent component by an api call which sets the token value with "this.accessToken = response.data". Then, <Panel accessToken={this.accessToken} />

Component do not re-render based on local instance variable, in your case this.accessToken.

You need to actually set the token in state, and then pass it to child component.

this.setState({accessToken : response.data})

And then pass it from state,

<Panel accessToken={this.state.accessToken} />
Sign up to request clarification or add additional context in comments.

Comments

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.