I am having a very strange issue with Reactjs's setState function. It seems to want me to structure pieces of my code in a very specific way or it won't work. I have no idea why this causes a problem as both structures look the same to me but behave in different ways.
I am using Browserify and Babelify to transpile and gulp-uglify to minify my code. It can be that one or a combination of these building steps causes the issue but I can't tell which (and thus I also don't know if and where to submit an issue)
Here is the relevant section of my code:
export default class VideoAppScreen extends React.Component {
constructor( props ) {
super( props );
this.state = {
playing: 0,
playlist: []
};
}
addVideo( video ) {
this.setState( ( previousState ) => {
return {playlist: previousState.playlist.push( video )};
});
}
onEnd( event ) {
console.log( "onEnd", event, this.state );
this.setState( ( previousState ) => {
return {playing: previousState.playing + 1};
});
}
render() {
// stuff
}
}
As you can see the setState blocks are formatted like this:
this.setState( ( previousState ) => {
return {item: value};
});
Like this the addVideo method causes the error: Uncaught TypeError: t.playlist.push is not a function
.
If I change the blocks to be like this:
this.setState( ( previousState ) => {item: value} );
The addVideo method works but the onEnd method stops working (without causing an error, it just doesn't update the state)
I can't figure out why these don't work the same way... For formatting purposes I'd like to both have them the same style but it seems that they only work when formatted in either style.
So as it turns our Array.prototype.push()
behaves differently than I expected, it returns the length of the array with the new element added onto it see mdn documentation.
I was basically resetting my playlist from []
to 1
and ofcourse numbers don't have a function push...
I can't tell why the other style of formatting did function as expected... The babelified code seems like it shouldn't work (and didn't work when I changed another function to look the same)