I am very new to react and redux. I am trying to update state in reducer using below.
export default function ReducersTodos(state = [], action) {
switch (action.type) {
case ADD_TODO:
state = [...state, {
id: state.length? state.length+1: 1,
text: action.value,
like: 0
}]
return state
break;
case ADD_LIKE:
state = state.map(todo => todo.id === action.id ? { ...todo, like: todo.like+1 } : todo)
return state
break;
case DIS_LIKE:
state = state.map(todo => todo.id === action.id ? { ...todo, like: todo.like-1 } : todo)
return state
break;
default:
return state
}
}
Like Component
export class Like extends React.Component {
constructor(props){
super(props);
// This binding is necessary to make `this` work in the callback
this._handleClickAdd = this._handleClickAdd.bind(this);
this._handleClickSub = this._handleClickSub.bind(this);
}
_handleClickAdd = function(e) {
e.preventDefault();
this.props.addLike(this.props.task.id);
}
_handleClickSub = function(e) {
e.preventDefault();
this.props.disLike(this.props.task.id);
}
render() {
return (
<div>
Like {this.props.task.like}
<button className="btn btn-primary" onClick={this._handleClickAdd} {...this.props.task.like}>+</button>
<button className="btn btn-danger" onClick={this._handleClickSub} {...this.props.task.like}>-</button>
</div>
);
}
}
function mapDispatchToProps(dispatch) {
return {addLike: bindActionCreators(addLike, dispatch),
disLike: bindActionCreators(disLike, dispatch)}
}
//set props
const mapStateToProps = (state, ownProps) => ({todos : state.todos});
Like = connect(mapStateToProps, mapDispatchToProps)(Like)
When I am trying to hit like or dislike button.
it re-rendered the whole list and UI look very weird.
is there any way to update only part of the array without looking up into the whole array.
Working code available on GitHub https://github.com/vinaypost/todos
CodepenandJSbin. so I have uploaded my code to GitHub github.com/vinaypost/todos