0

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} />
        )
    }
});
2
  • It looks like localStorage.getItem('selectedImages'); is returning null so of course ids can't be accessed from null. Also, you know that push returns the array length right? not the actual array.
    – azium
    Commented Apr 27, 2016 at 18:49
  • 4
    localStorage can only hold strings .. you have to JSON serialize
    – Matt
    Commented Apr 27, 2016 at 18:50

1 Answer 1

2

It seems like your app has following flow (considering empty localStorage):

  1. getInitialState: returns { ids : [] } but sets nothing to localStorage

  2. render: render your component. On click goes to next step

  3. selectImage:let selectedImages = localStorage.getItem('selectedImages'); Pay attention that selectedImages is null cause you haven't set to localStorage anything yet

  4. selectImage: let selectedImagesArray = selectedImages.ids.push(key); throws your error "Uncaught TypeError: Cannot read property 'ids' of null."

And pay attention to @Matt's comment. Setting object to localStorage means settings string "[object Object]", you have to serialize your data before you set it (JSON.stringify) and deserialize after your get it (JSON.parse).

Not the answer you're looking for? Browse other questions tagged or ask your own question.