In my react app, I have two components(personal items list and random items list). In my random items list component, I can click on the item and add it to my personal items list component. However, when I do that it replaces my other items in my personal items state with the new item I just added. I simply want to add on to my personal items list.
//Update Items List
export const updateItemsList = (data) => ({
type : UPDATE_ITEMS_LIST,
payload: data
});
//Items List Reducer
const initialState = {
items: [],
loading: false
};
export default function(state = initialState, action){
switch(action.type){
case UPDATE_ITEMS_LIST:
return{
...state,
items: action.payload,
loading: false
};
default:
return state;
}
}
//Select Item To Add
export const addItemToList = (itemId) => (dispatch, getState) =>{
const config = {
headers:{
"Content-Type": "application/json"
}
};
axios.post(`/api/items/addItem/${itemId}`, {}, config)
.then(res => {
dispatch({
type: ADD_ITEM_SUCCESS,
payload: res.data
})
dispatch(updateItemsList(res.data, ...getState().itemsList.items));
})
.catch(err =>{
dispatch({type: ADD_ITEM_ERROR}));
});
};
//React User's Item List Component
class Items extends Component{
componentDidMount(){
this.props.userItems();
}
render(){
const { items, loading} = this.props.itemsList;
return(
<React.Fragment>
{loading === true ? (
<div>
<div>
<h1>Your Items Are Loading...</h1>
</div>
</div>
):(
<div>
{items.map(item => (
<React.Fragment key={item.id}>
<div>
<div>
<h3>{item.name}</h3>
</div>
</div>
</React.Fragment>
))}
</div>
)}
</React.Fragment>
);
}
};
export default connect(mapStateToProps, mapActionsToProps)(Items);
//React Random Item List Component
class RandomItems extends Component{
handleAddItem = (id) =>{
this.props.addItemToList(id);
}
componentDidMount(){
this.props.getRandomItemsList();
}
render(){
const { randomItems, loading} = this.props.randomItemsList;
return(
<React.Fragment>
{loading === true ? (
<div>
<div>
<h1>Loading Random Items...</h1>
</div>
</div>
): (
<div>
{randomItems.map(item => (
<React.Fragment key={item.id}>
<div>
<div>
<h3>{item.name}</h3>
<button onClick={this.handleAddItem.bind(this, item.id)}>Add To List</button>
</div>
</div>
</React.Fragment>
))}
</div>
)}
</React.Fragment>
)
}
};
export default connect(mapStateToProps, mapActionsToProps)(RandomItems);
assuming res.data
is the new item you just added, when you dispatch updateItemList I think you missed the square bracket for the array. so you just sending res.data
in the payload. it should be like this
updateItemsList([res.data, ...getState().itemsList.items])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.