I'm surprised here. Maybe you can make it clear for me.
Here is a react riddle that I can't understand:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import _ from 'lodash';
import './style.css';
import FavoritesListItem from '../../components/FavoritesListItem';
class Favorites extends Component {
handleSaveFavorites() {
console.log(this.props.favoritesList);
}
handleClearFavorites() {
localStorage.clear();
}
handleConsoleLogLocalFavorites() {
console.log('without JSON.parse', localStorage.getItem('lastSavedFavourites'));
console.log('with JSON.parse',JSON.parse(localStorage.getItem('lastSavedFavourites')));
}
render() {
if (this.props.favoritesList.length === 0) {
return (
<p className="FavoritesListItem-text">
There are no favorite recipes to show!
</p>
);
}
const favoritesListGenerator = this.props.favoritesList.map(oneFav => {
const keyOneFav = _.uniqueId('favorite_');
return (
<FavoritesListItem key={keyOneFav} title={oneFav[0]} link={oneFav[1]} />
);
});
return (
<div>
<div className="container">
<div className="row justify-content-xl-center">
<ul className="col-xl-12">{favoritesListGenerator}</ul>
<button onClick={this.handleSaveFavorites}>Save</button>
<button onClick={this.handleClearFavorites}>Clear</button>
<button onClick={this.handleConsoleLogLocalFavorites}>Local</button>
</div>
</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
favoritesList: state.favoritesList,
readFavorites: state.readFavorites,
};
}
export default connect(mapStateToProps, null)(Favorites);
Why this.props.favoritesList
is working fine and reading data inside favoritesListGenerator
, but the same this.props.favoritesList
doesn't want to work inside handleSaveFavorites
?
Screenshot of an error:
I don't know what else shoud I add so:....
EDIT:
So I added
constructor() {
super();
this.handleSaveFavorites = this.handleSaveFavorites.bind(this);
}
to my code and now it works!
AND
I think that
<button onClick={() => this.handleSaveFavorites()}>Save</button>
would also work!