nathanstitt/react-braintree-fields

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

HOllarves opened this issue · 1 comments

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!

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