Home > Mobile >  React State Hook initialised to [] still shows type as undefined
React State Hook initialised to [] still shows type as undefined

Time:07-20

Code:

const [input, setInput] = useState('');
const [studentList, setStudentList] = useState([]);

useEffect(() => {
  console.log(studentList)
  console.log(studentList.type)
}, [studentList]);

return (
  <div id="add-students-input-div">
    <input
      type="text"
      id='add-students-input'
      value={input}
      placeholder='Enter a student to the database'
      onChange={(event) => {
        setInput(event.target.value)
      }}
    />
    <div id="add-students-button" onClick={() => {
      setStudentList([document.getElementById('add-students-input').value, ...studentList])
      setInput('')
     }}>
      <p>Add</p>
    </div>
  </div>
)

Problem: The print statement for studentList is returning the array but the print statement for studentList.type is undefined at all times, even after elements are added to the array.

How can I ensure that studentList.type returns Array.

CodePudding user response:

studentList in your code will ever be an array, empty when you initialize the state. If you want to check if there is something in the array you have to use studentList.length

CodePudding user response:

As mentioned in the comments, arrays do not have a type property.

Your studentList state value is always an array; there is no need to check its type.

One thing you do appear to be doing incorrectly is updating studentList when you click you button (<div>). In short, you really shouldn't need to use DOM methods in React.

To update your array with the value from your input state, use this...

const handleClick = () => {
  setStudentList((prev) => [input, ...prev]);
  setInput("");
};

and

<div id="add-students-button" onClick={handleClick}>
  <p>Add</p>
</div>

See useState - Functional updates for information on how I'm using setStudentList()

CodePudding user response:

Altough previous contributors solved your problem by eliminating it in other place, I would like to answer this:

How can I ensure that studentList.type returns Array

If you want to make sure your variable is an array, you may use isArray() static method of Array:

Array.isArray(studentList) // returns true if array or false if not
  • Related