Home > database >  How do you update state in parent component from a child component when an event takes place in the
How do you update state in parent component from a child component when an event takes place in the

Time:12-31

I have to update state of the parent class component from child functional component only when a click event takes place in the parent component. Right now I've access of the data from child to parent component but when I update the state I get error, maximum depth reached. So I thought it'd be better to update the parent's state from child only when the certain event takes place in the parent component but I'm unable to find any approach. Could you please show some light?

CodePudding user response:

From your description, the best thing to do is to lift state up from the child to the parent so that the information you currently only have in the child is available in the parent (which can provide it to the child as a prop). Then, the child isn't involved in this at all, the event in the parent updates the parent's state, which is standard.

But if you absolutely can't do that:

It's taking you off the beaten path, but you could:

  1. Have the parent pass the child two things:
    1. a means of subscribing to an event from the parent
    2. a function to call to update the parent's state
  2. Have the child subscribe to the event
  3. Have the parent raise the event the child subscribes to when the click occurs
  4. Have the child respond to that event by calling the function from (1)(2) above

While that would work, it's a bit convoluted. So again, if you can avoid it, move the state needed for the update from the child to the parent and keep the entire update in the parent.

  • Related