-4

I can't put state in a constant. I'm managing state in a function where on button click I only increment it by 1. That works fine, but when I try to use that state somewhere else in application I get this error.

I've tried putting state in variable first then put it in constant.

          const Gallery = (
                <div className={classes.Gallery}>
                    <Image src={images[{...this.state.imageNumber}].original} />
                    <button onClick={this.nextImageHandler}>
                        Click Me!
                    </button>
                </div>
          );
  • 4
    This `images[{...this.state.imageNumber}].original` doesn't make sense. You are indexing `images` with an object. Take a look at [Spead in object literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Spread_in_object_literals) – SpencerPark Apr 10 '19 at 18:20
  • When I set it to images[0].original it works just fine. this.state.imageNumber is just a number in state that changes – Marko Đurić Apr 10 '19 at 18:25
  • 2
    Should be `images[this.state.imageNumber].original` probably – adiga Apr 10 '19 at 18:25

1 Answers1

0

The issue is you are trying to access a property of a javascript variable without first checking if it is defined. See Detecting an undefined object property

You are also not indexing your array properly and you are abusing the spread operator (...). There is no reason to spread a number. ...5 has no real semantic meaning.

console.log({...5}); // yeilds {}

That means you are trying to do images[{}] and means you are trying to index your array with the string [object Object]. This is probably not what you meant to do. You should just do images[this.state.imageNumber].

With regards to your error Cannot read property 'original' of undefined, I imagine it's likely because you never initialized your state. As a result, this.state.imageNumber is undefined. That means you are indexing your array like images[undefined]. What you should do is either handle the undefined case or initialize your state to some sensible default.

Something like:

class MyComponent extends React.Component {
    state = { imageNumber: 0 };
    ...
    render() { ... }
}

At any rate, I would suggest you consider taking a javascript ramp-up course, as you are confusing fundamentals of javascript with reactjs and this may make it difficult for you to debug problems with either.