I'm diving into the world of Redux and feeling a bit confused about how to update data without mutating it.
Here is my current data structure:
{
postOwnerName:"",
postTags:[],
photos:[
{
id:dc5c5d7c5s,
caption:null
},
{
id:dccccccc5s,
caption:null
}
]
}
When the function triggers with this line of code:
this.props.updateCaption(id, caption)
I want my Reducer to update the data structure based on the provided id without mutating it.
import * as types from '../Actions/actionTypes';
const initialState = {
postOwnerName:"",
postTags:[],
photos:[],
};
export default function uploadReducer(state=initialState, action) {
switch (action.type){
case types.SETPHOTOSTATE:
return Object.assign({}, state, { photos: state.photos.concat(action.payload) });
case types.SETCAPTIONTEXT:
return (
Object.assign({}, state, {
photos: state.photos.map((data) => {
if(data.id === action.payload.id) {
return Object.assign({}, data, {caption: action.payload.caption})
} else {
return data
}
})
})
)
default:
return state
}
}