Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Arrow Function Component - setState is not defined

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>
 );
};
like image 492
Raghav Avatar asked Aug 07 '19 12:08

Raghav


People also ask

Why is my setState undefined?

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.

Why is setState not a function?

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 .

How do I use setState in React?

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.

How do you fix is not a function React?

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.


1 Answers

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>
 );
};
like image 196
Dupocas Avatar answered Oct 13 '22 01:10

Dupocas