0

My view looks something like this (but I've slimmed it down for simplicity)

view.jsx

import * as R from 'ramda';
import { Validate } from 'src/utils/validate';

class example extends Component {
    constructor(props) {
        super(props);

        this.state = {
            model: EMPTY_MODEL,
            validation: EMPTY_VALIDATION,
        };
        this.validate = R.bind(Validate, this);
    }

    render() {
        <div>
            <input
                id="example"
                type="text"
                onChange={ this.validate }
            />
        </div>
    }
}

validate.js

import * as R from 'ramda';

export const Validate = ({ currentTarget }) => {
    console.log(this); // outputs: {}
    console.log(this.state); //outputs: undefined
    debugger; //console.log(this.state); outputs { model: {}, validation: {} }

    let { validation } = this.state; //Error: Cannot read prop 'validation'of undefined
    const { id, value } = currentTarget;

    switch (currentTarget.id) {
        case 'example':
            if(value.length < 4) {
                this.setState({
                    validation: R.assocPath([id, 'valid'], false, validation),
                });
            }
            break;
        default:
            break;
    }
}

Core Question

  • What do I need to do to have access to this.state.validation inside of validate.js using bind? (I would like to avoid passing this to validate as a param)

Questions to understand

  • Why does console output undefined in validate.js, but if I output variables during the debugger I get the expected values?
Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
  • Because its a functional component or stateless component so this.state won't be available in functional components. Functional components in react is same like pure functions in javascript – Hemadri Dasari Oct 19 '18 at 17:41
  • 1
    Possible duplicate of [Can you bind arrow functions?](https://stackoverflow.com/questions/33308121/can-you-bind-arrow-functions) – skyboyer Oct 19 '18 at 17:48
  • Functional component (hence the constructor with state). But I can have that function inside of `view.jsx` and it will work fine – Seth McClaine Oct 19 '18 at 17:50
  • Thanks @skyboyer I think you are correct **Confirmed** – Seth McClaine Oct 19 '18 at 17:50

2 Answers2

1

As skyboyer eluded to, the issues is binding a arrow function

In validate.js changed

export const Validate = ({ currentTarget }) => {

to

export const Validate = function ({ currentTarget }) {
Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
-1

Can you try this.validate = Validate.bind(this); instead?