On an onclick event in React (don't think React's causing the problem, I think it's how I'm handling the object & array), I'm trying to grab a local storage variable and push an element (key) to it, however it's throwing the error 'Uncaught TypeError: Cannot read property 'ids' of null.'
Here's the code:
import React from 'react';
import Images from './images';
export default React.createClass({
getInitialState() {
// If doesn't exist, create empty instance
let selectedImages = localStorage.getItem('selectedImages') ? localStorage.getItem('selectedImages') : { ids : [] };
return selectedImages;
},
selectImage(key) {
// get localstorage
let selectedImages = localStorage.getItem('selectedImages');
// Create instance of ids array and push key
let selectedImagesArray = selectedImages.ids.push(key);
// set .ids as selectedImagesArray
selectedImages.ids = selectedImagesArray;
// Set new local storage
localStorage.setItem('selectedImages', selectedImages);
},
render() {
let selectedImages = localStorage.getItem('selectedImages');
return (
<Images items={feedData.items}
selected={selectedImages}
selectImage={this.selectImage} />
)
}
});
localStorage.getItem('selectedImages');
is returningnull
so of courseids
can't be accessed fromnull
. Also, you know thatpush
returns the array length right? not the actual array.localStorage
can only hold strings .. you have to JSON serialize