Nane Nane - 14 days ago 5
React JSX Question

How to Increase Post like without Mutating state in redux?

I am new to redux.I know this is a newbie question but I can't find any correct solution.I am building simple post with like count increase when someone clicks
this is my Code
My question is How to change or increase likes count for particular post without mutating state and what is most efficient way to do this when big array objects of post containing pictures

App.js

import React from 'react';
import {connect} from 'react-redux';
import uuid from 'uuid'
import * as inputActions from './actions/addinput';



class Main extends React.Component{
constructor(props){
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.handlelike = this.handlelike.bind(this);
}
handleSubmit(e){
e.preventDefault();
console.log(e.target.name.value)
this.props.addinput
(
{
id:uuid.v1(),
name:e.target.name.value,
likes:0

}

)
}
handlelike(id){


this.props.likes(id)
}
render(){

return(
<div>
<form onSubmit={this.handleSubmit}>
<input type="text" name="name"/>
<input type="submit"/>
</form>
<div>
{this.props.inputs.map((data) => {
return(
<div key={data.id}>
<p >{data.name} <button onClick={ () => this.handlelike(data.id)}> {data.likes} Like it</button></p>
</div>

)
})}
</div>
</div>
)
}
}

const mapStateToPros = (state) => {
return{
inputs:state.addinput
}
};
const mapDispatchToProps = (dispatch) => {
return {
addinput: input => dispatch(inputActions.postinput(input)),

likes:id => dispatch(inputActions.likes(id))
}
};

export default connect(mapStateToPros,mapDispatchToProps)(Main)


actions.js

import * as actionTypes from './actionTypes';

export const postinput = (input) =>{
console.log(input,"From Action")
return{
type:'POST_INPUT',
payload:input
}
}

export const likes = (id) => {

return{
type:'LIKES',
payload:id
}
}


reducers.js

export default (state = [],action) => {
switch (action.type){
case 'POST_INPUT':
return[
...state,
Object.assign({},action.payload)
];
case 'LIKES':
export default (state = [],action) => {
switch (action.type){
case 'POST_INPUT':
return[
...state,
Object.assign({},action.payload)
];
case 'LIKES':
//start work from here
return state.map((post) => {
console.log(post.id);
if (post.id === action.payload) {
return Object.assign({}, post, { likes: post.likes+1 })
} });

default:
return state
}

}

Answer

As you aware that you should not mutate the state/store in redux, you can return new state as shown below,

case 'LIKES': 
 return state.map((post) => { 
   if (post.id === action.payload) { 
      return Object.assign({}, post, { likes: post.likes+1 }) } 
   }
   return post
)
Comments