score:9

Accepted answer

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>
 );
};

score:0

For the future, make sure you understand that you're using a function component in this code; function components are meant to be stateless components. That is why you get the error about there being to state defined. If you plan to use states, then go with a class component which are used as stateful components. With class components, you can set the initial state by using a constructor that accepts "props" as an argument before your render method. To make this code work, switch this function component into a class component and define the initial state in the constructor.

score:1

To use state in functional components we use the so called react hooks. In your case this hook can look like this.

 const [state, setState] = React.useState({
   selectedSlot: { "0": "00", "1": "11" },
   cal: 1
 })

We use array deconstruction here. The first value is the state itself and the second value is the method we use to set the state. inside React.useState we pre-define our initial state. With setState you can mutate our current state.

To overwrite current state data we simply set the state to the allready existing property. If the property doesnt exist, a new one will be added to the state.

And ofcourse, since its a hook it has to be imported.

import React, { useState } from 'react';

score:2

you cannot use setState inside functional component.In order to do so you have to use useState of react hook.

import React,{useState} from 'react'
 const AddAssetActivity = props => {
 let { variations, slots, priceStructure } = props;

const [state,setState]=useState({
 selectedSlot:{},
 cal:1

})

 let handleChange = (event, value) => {
  const newState = {...state}
   let selectedSlot = newState.selectedSlot;
   selectedSlot[value.variation] = value.slot;
   setState({ ...newState, selectedSlot });
 };

 return (
   <div>

   </div>
 );
};

Related Query

More Query from same tag