I have a list of graphics received from redux state. I have also created a state hook whose default value is the first object in this list. Why is the variable currentFile undefined ? I searched for similar topics that would explain this issue to me, but I didn't find anything similar. The strange thing is that when I display the default value itself in the console I get the expected result.
When I type a number in the index of the image list, e.g. images[0], I also get an undefined value.
Below I put a picture of the console result.
Code:
function Images() {
const [activeIdx, setActiveIdx] = useState(0)
const dispatch = useDispatch()
const imagesList = useSelector((state) => state.imagesList)
const { loading, error, images } = imagesList
const [currentFile, setCurrentFile] = useState(images[activeIdx])
console.log(images[activeIdx])
console.log(currentFile)
useEffect(() => {
dispatch(listImages())
}, [dispatch)
return (
...
)
}
useState(initialValue) will only use initialValue on the first render and does not change after re-renders. graphics[activeIdx] can be undefined so this will log undefined as a currentFile value.
You should write listener which will save every new value of graphics[activeIdx] to your state:
useEffect(() => {
setCurrentFile(images[activeIdx])
}, [images])