Reputation: 1948
I have stumbled upon a problem when adding an element inside an object inside an array. What I would like to do is add the element isFavorite: true
. I am currently attempting to do so by doing the folowing:
{
...state,
list: state.list.map(item =>
item.id === action.payload.libraryContentId ?
{ ...item, isFavorite: true }
: item)
}
The payload contains the following object:
{
id: 1,
name: 'Name',
libraryContentId: 3
}
But the above does not seem to be updating the item and add the element. What do you guys suggest?
Edit: More examples of the code.
Action:
try {
const response = await axios.post(URL, {params});
dispatch({ type: ADD_FAVORITE, payload: response.data });
catch (error) {
dispatch({ type: ERROR });
}
Response Data:
{
id: 117
libraryConntentId: 245
}
List item sample:
{
id: 245,
name: 'Name',
isFavorite: false
}
Thank you!
Upvotes: 0
Views: 88
Reputation: 573
Maybe something like this (check testMethod):
class Hello extends React.Component {
constructor(props){
super(props);
let testData = [
{
id: 1,
name: 'Name1',
isFavorite: false
},
{
id: 2,
name: 'Name2',
isFavorite: false
},
{
id: 3,
name: 'Name3',
isFavorite: false
},
{
id: 4,
name: 'Name4',
isFavorite: false
},
{
id: 5,
name: 'Name5',
isFavorite: false
}]
this.state = {
boolvar: true,
numbar: 2,
list: testData
}
this.testMethod = this.testMethod.bind(this);
console.log("Original state");
console.log(this.state);
}
testMethod(){
let testAction = {
payload: {
libraryContentId: 3
}
}
this.setState((prevState, prevProps) => {
return {
list: [...prevState.list.map(item => item.id === testAction.payload.libraryContentId? {...item, isFavorite: true}: item)]
}});
}
render(){
console.log(this.state);
return (<div><button onClick={() => {this.testMethod()}}>Test It</button></div>);
}
}
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
Upvotes: 1