0

I have an array of variable names stored in the state of my functional component - ['firstName', 'lastName', 'userName]. I'm looping over this array to verify that these values are not null in state.

Normally, with a class-based component, I'd be able to use these strings to get their values from state like: this.state['firstName']. But I'm using a functional component that used the useState hook to initialize these values. If I'm looping through my string array, what do I call to get the value from state?

This is sample code to give you an idea of what I'm trying to accomplish:

const MyComponent = (props) => {
   const [ firstName, setFirstName ] = useState(null);
   const [ lastName, setLastName ] = useState(null);
   const [ userName, setUserName ] = useState(null);
   const [ otherField, setOtherField ] = useState(null);

const requiredFields = ['firstName', 'lastName', 'userName'];

const verifyRequiredFields = () => {
   requiredFields.forEach((field) => {
      if (state[field] !== null) { ... } // HERE IS THE PROBLEM - HOW DO I GET STATE?
   }
}
...
L Becker
  • 515
  • 7
  • 23

2 Answers2

1

create one state for the componet which combine the firstName,lastName,userName like this :

const MyComponent = (props) => {
   const [state, setState] = useState({firstName:"",lastName:"",userName:""});
   const [ otherField, setOtherField ] = useState(null);

const requiredFields = ['firstName', 'lastName', 'userName'];

const verifyRequiredFields = () => {
   requiredFields.forEach((field) => {
      if (state[field] !== null) { ... } // HERE IS THE PROBLEM - HOW DO I GET STATE?
   }
}
...

and if you are handling input change for each field you can do it like this now:

const handleChange = (event)=>{
const {name,value} = event.target
setState(current=>({...current,[name]:value}))
}

<input name="firstName" value={state.firstName} onChange={handleChange}/>
adel
  • 3,116
  • 1
  • 4
  • 15
0

maybe use eval:

eval(field) // if the value of field is 'firstName',
            // then eval(field) will be the value of firstName.
yaya
  • 6,363
  • 1
  • 30
  • 34