I have a 2d array, which I can push elements to. The issue i'm running into is the fact that when i print the contents, there is always a blank element at index 0. I do not know where this is coming from?
const [array, setArray] = useState([[]]);
// call this code 4 times
const updatedArray = [...array, ['test', 'test2']];
setArray(updatedArray);
The Problem here is
...array
since the initial value of the array is
[].
So array[0] would be equal to [] and you append your new values beginning from array[1] on.
What you want to do is const updatedArray = [['test', 'test2']]; since you do not want the initial value to be kept.
Sometime this issue occurs with state.
In case of hooks, you should use useEffect hook, As below-
const [fruit, setFruit] = useState('');
useEffect(() => {
console.log('Fruit', fruit);
}, [fruit])
This saved my day, Hope will help you too!!!