samedi 22 mai 2021

How to deal with duplicated function code that alters parent state

Say we got a Page-component that delegates the rendering of notifications to a Notification-component. The Page-component's render method contains the following ...

{this.state.notifications &&
            <Notifications
                     notifications={this.state.notifications}
                     removeNotifAt={index => this.setState(prevState => {
                         const copy = [...prevState.notifications]
                         copy.splice(index, 1)
                         return { notifications: copy }
                     })}
                     removeNotifyBy={id => this.setState(prevState => {
                         const copy = [...prevState.notifications]
                         const index = copy.findIndex((notif, _) => { return notif.id === id })
                         copy.splice(index, 1)
                         return { notifications: copy }
                     })}
            />
}

... as you might notice, Notifications require some rather large function to alter the state of its parent. Since they access this.state, these functions have to be defined in the parent of Notifications, in this case Page.

Now, one can imagine that multiple pages have notifications that needs rendering and so they all have to code-duplicate the code snippet above. As we all know, code-duplication is bad, so how can we best avoid it?

It's impossible to extract the functions removeNotifyAt and removeNotifyBy out into functions defined in, say, Notifications.js since they need to access this.state.

So, what's the react-way of dealing with such duplicate functions that you can't extract away because it needs to access this.state? I suppose I am not the first one stumpling upon this, giving how trivial of a case this is.

Aucun commentaire:

Enregistrer un commentaire