Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React functional component - Cannot read property 'tokenize' of undefined #20

Closed
HOllarves opened this issue Mar 16, 2020 · 1 comment
Closed

Comments

@HOllarves
Copy link

Hi!

I'm trying to implement your lib in a React functional component.

However I'm getting a Cannot read property 'tokenize' of undefined error when attempting to get the reference for the tokenize function.

Here's a summary of my code:

import React, { useEffect, useState } from 'react'
// Braintree
import { Braintree, HostedField } from 'react-braintree-fields'

const Checkout = ({ location }) => {
    const [tokenize, setTokenizeFunc] = useState(null)
    return (
        <Braintree
                    className={isReady ? '' : 'disabled'}
                    authorization='sandbox_xxxxxxxxxxxxx'
                    onAuthorizationSuccess={onAuthorizationSuccess}
                    onDataCollectorInstanceReady={onDataCollectorInstanceReady}
                    onError={handleError}
                    onCardTypeChange={onCardTypeChange}
                    getTokenRef={ref => setTokenizeFunc(ref)}
                    styles={{
                        'input': {
                            'font-size': 'inherit',
                        },
                        ':focus': {
                            'color': 'blue'
                        },
                    }}>
                        [...]
        </Braintree>
    )
}

I've also tried doing something like getTokenRef={ref => setTokenizeFunc.bind(Braintree, ref)} but still no luck.

Is this implementation possible? Or should I just stick to class components in this scenario?

Thank you!

@nathanstitt
Copy link
Owner

Thanks for the report, I learned something new that I haven't seen documented before. If you call setState with a function, the function is immediately called and whatever it returns is what's stored. I figured this out by using this bit of code and looking at the stack:

            getTokenRef={ref => setTokenizeFunc(() => {
                debugger
                ref
            })}

Afterwards I also found https://medium.com/@pshrmn/react-hook-gotchas-e6ca52f49328 that also talks about it.

I'll convert the demo script to a functional version and note this in the README

nathanstitt added a commit that referenced this issue Mar 16, 2020
Illustrates how to work around issue #20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants