I am trying to setState in an arrow function component but getting an error "setState is not defined".
I tried setting state in handleChange using setState({ selectedSlot })
and this.setState({ selectedSlot })
but nothing worked.
const AddAssetActivity = props => {
let { variations, slots, priceStructure } = props;
let state = {
selectedSlot: { "0": "00", "1": "11" },
cal: 1
};
let handleChange = (event, value) => {
let selectedSlot = state.selectedSlot;
selectedSlot[value.variation] = value.slot;
setState({ selectedSlot });
};
return (
<div>
</div>
);
};
The "cannot read property 'setState' of undefined" error occurs when a class method is called without having the correct context bound to the this keyword. To solve the error, define the class method as an arrow function or use the bind method in the classes' constructor method.
Cause of the error The reason why this error occurs is because of a concept called Closures in JavaScript. That means the scope/context of the function updateCounter and the class App are not the same. This means App and updateCounter have a different this .
The setState() Method State can be updated in response to event handlers, server responses, or prop changes. This is done using the setState() method. The setState() method enqueues all of the updates made to the component state and instructs React to re-render the component and its children with the updated state.
The React. js "Uncaught TypeError: X is not a function" occurs when we try to call a value that is not a function as a function, e.g. calling the props object instead of a function. To solve the error, console. log the value you are calling and make sure it is a function.
To implement stateful logic inside functional components use hooks
:
const AddAssetActivity = props => {
let { variations, slots, priceStructure } = props;
const [state, setState] = React.useState({
selectedSlot: { "0": "00", "1": "11" },
cal: 1
})
let handleChange = (event, value) => {
const _state = {...state}
let selectedSlot = _state.selectedSlot;
selectedSlot[value.variation] = value.slot;
setState({ ..._state, selectedSlot });
};
return (
<div>
</div>
);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With