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?
}
}
...