reactjsstatereact-functional-componentreact-class-based-component

this.setState is not assigning a value to state, returning "undefined"


So I'm trying to assign a state to a parent class component from a child functional component.

The issue I'm running into is that the state of the parent doesn't seem to be getting set with the value that is passed from the child component. When I log the value that is being passed into setState() it's correct, but when I try to log this.Value, I get undefined.

I've done many searches and I think I've bound the function properly, but please advise.

Parent:

class Scor extends React.Component {
constructor(props) {
    super(props);
    this.state = { checked: false, weights: false, numKeysValue: 1 };
    this.handleNumKeys = this.handleNumKeys.bind(this);
}
handleNumKeys(value) {
    this.setState({ numKeysValue: value });
    console.log(value);
    console.log(this.numKeysValue);
}

Child component call in parent component:

<QuestionDropDown
    question="How many answer keys do you have?"
    chosenValues={numAnswerKeys}
    numKeysValue={this.handleNumKeys}
    defaultValue="1"
/>

Child component code:

function Questiondropdown(props) {
const [answerOption, setAnswerOption] = React.useState(props.defaultValue);
const handleChange = (event) => {
    setAnswerOption(event.target.value);
    props.numKeysValue(parseInt(event.target.value));
};
return (
<TextField
    select
    helperText={props.helpText}
    value={answerOption}
    onChange={handleChange}
/>

Essentially my problem is that whatever number I select in the child component dropdown, i.e. "3", the value of this.numKeysValue is not set, but returns as undefined. In this same example, the code

console.log(value);
console.log(this.numKeysValue);

in the parent returns

3
undefined

After the

this.setState({ numKeysValue: value });

call

I'm happy because I finally got something back from the child component, which I've been struggling with, but why can't I set the state of the parent with it?

Any help would be greatly appreciated.


Solution

  • Access state in class components like this this.state.numKeysValue