1

I'm trying to create a component which has very less dependencies and requires almost no extra code for using it inside another component. I'm stuck where i need to set the state because setState method requires this context.

Currently I'm sending this, as a context to the method defined in my Library Component.

export const showSnackbarNotification = (context, msg, variant) => {
  context.setState({
    [`notificationMsg`]: msg, 
    [`notificationToggle`]: true,
    [`variant`]: variant
  })
}

And I'm calling this function like below:

showSnackbarNotification(this, "checking the function", "error");

But I don't want the user to send this context via method parameter. Is there any way that i can execute the method with the context of where it is called. So showSnackbarNotification definition becomes:

export const showSnackbarNotification = (msg, variant) => {
  this.setState({
    [`notificationMsg`]: msg, 
    [`notificationToggle`]: true,
    [`variant`]: variant
  })
}

and still set the state of Component where i called showSnackbarNotification method.

Maher Shahmeer
  • 148
  • 1
  • 10

1 Answers1

1

Use a regular function:

export function showSnackbarNotification(msg, variant) {
  this.setState({
    [`notificationMsg`]: msg, 
    [`notificationToggle`]: true,
    [`variant`]: variant
  })
}

when you call it you can use .call to set the context:

showSnackbarNotification.call(this, "checking the function", "error");

Arrow functions always have the context in which they are declared. Regular functions adopt the context in which they are called.

Are 'Arrow Functions' and 'Functions' equivalent / exchangeable?

Ross Allen
  • 43,772
  • 14
  • 97
  • 95
  • I tried that @Ross Allen, But this doesn't work. Error `TypeError: Cannot read property 'setState' of undefined ` – Maher Shahmeer Apr 19 '19 at 15:37
  • @MaherShahmeer I updated my answer. When you call it, you can use `.call` to set the context. – Ross Allen Apr 19 '19 at 15:39
  • I suggest seeing if a [higher-order component](https://reactjs.org/docs/higher-order-components.html) would suit your use case better though. The pattern you're using now is more like a "mixin", and they become difficult to understand in larger codebases; it's difficult to know what is controlling the state of a given component. – Ross Allen Apr 19 '19 at 15:41
  • I understand @Ross Allen. Your updated answer worked for me now. I'll surely look into HOC right now. (y) – Maher Shahmeer Apr 19 '19 at 15:44