Next.js Discord

Discord Forum

update parent state by child component

Unanswered
French Lop posted this in #help-forum
Open in Discord
French LopOP
I have a Component that updates a state in the parent component by clicking an button.
It works fine but console error:

Cannot update a component while rendering a different component

Is there a way to achieve a similar behavior without an error/warning?

This is my code:

Parent:
const [showBanner, setShowBanner] = useState(true); {showBanner && notifications ? ( <NotificationBanner notifications={notifications} setShow={setShow} /> ) : null}

Child:
type NotificationBannerProps = { setShow: (show: boolean) => void, notifications: NotificationBannerModel[], }; const dismissAndStore = () => { setShow(false); }; <Button variant="text" onClick={dismissAndStore}>Ausblenden</Button>

13 Replies

Blue orchard bee
Can you create a repro of the bug in StackBlitz?
Also in your code you pass setShow to the child but the useState says setShowBanner, was that a typo?
Blue orchard bee
Right, these usually happen because of dirty state sets, I think using an arrow function rather than passing a value should solve your problem onClick: () => setShow(state => false)
French LopOP
i try this thanks
strange thing... the console error doesnt appear now
Blue orchard bee
Do you happen to change the Notifications value somewhere else?
Maybe you're setting it at the same time you're taking it off the DOM
French LopOP
Yeah if the banner gets rendered it checks if the banner was dismissed before (session storage) and if it’s dismissed then the show state is set to false.
Maybe I need to check bevor I render then Child component
Blue orchard bee
Yea that could be it, because just a setState shouldn't cause trouble
but if something else is listening for that state then there could be problems