Skip to content
This repository has been archived by the owner on Mar 27, 2021. It is now read-only.

The async example code violates react/no-did-mount-set-state #196

Closed
revmischa opened this issue Apr 10, 2018 · 1 comment
Closed

The async example code violates react/no-did-mount-set-state #196

revmischa opened this issue Apr 10, 2018 · 1 comment

Comments

@revmischa
Copy link

In re: https://github.com/stripe/react-stripe-elements#advanced-integrations

This async script tag solution works, but using the airbnb eslint preset, I get the error:
[eslint] Do not use setState in componentDidMount (react/no-did-mount-set-state)

See: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-mount-set-state.md

@jez
Copy link
Collaborator

jez commented Apr 10, 2018

Hey @revmischa! Thanks for bringing this up.

This is a known issue. You can read more about it here:
#154

The tl;dr is that React doesn't provide lifecycle methods that are granular enough for our needs. We need:

  • to be able to read the DOM (so that we can check if window.Stripe is available)
  • to set state before the first render

Such a life cycle method does not exist (see here).

What can be done?

  1. You can disable the ESLint rule. In cases where Stripe.js loads before componentDidMount is called, there will be a second render.
  2. You can do the setState in a setTimeout(fn, 0). You will still get a double render, but you don't have to disable the ESLint rule.
  3. You dynamically construct and inject the <script> tag in componentDidMount. You will still get a second render, and you will also have to wait longer, because Stripe.js won't be loaded in parallel with React's first render.
  4. You might (I'm not sure if this would work) be able to move the if (window.Stripe) check to the constructor, BUT this will definitely break server-side rendering, and might even lead to a race condition with the 'load' event. I would not recommend this.

I think your best bet is just to ignore the ESLint rule.

Hope that helps!

@jez jez closed this as completed Apr 10, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants