I have a .map function in a component:
let recentItemsMarkup = loading ? (
<p>Items are loading...</p>
) : (
items.map(item => (
<ShoppingItem
key={item._id}
id={item._id}
name={item.name}
createdAt={item.date}
/>
))
);
When I post an item, sometimes -not always- it duplicates on the view, but not in Database. DB is working properly, but somehow, after I post an item, it is not always sets the items properly, here are the action and the reducer:
//post item
export const postItem = newItem => dispatch => {
dispatch({ type: LOADING_UI });
axios
.post("http://localhost:5000/api/items", newItem)
.then(res => {
dispatch({
type: POST_ITEM,
payload: res.data
});
})
.catch(err => {
dispatch({
type: SET_ERRORS,
payload: err.response.data
});
});
};
and the reducer:
const initialState = {
items: [],
item: {},
loading: false
};
export default (state = initialState, action) => {
switch (action.type) {
case LOADING_ITEMS:
return {
...state,
loading: true
};
case GET_ITEMS:
return {
...state,
items: action.payload,
loading: false
};
case POST_ITEM:
return {
...state,
items: [action.payload, ...state.items]
};
case DELETE_ITEM:
return {
...state,
items: state.items.filter(item => item._id !== action.payload)
};
default:
return state;
}
};
I checked the Ids and Database, everything is ok, ids are unique vs. Why this happening?
and also Shopping Item component:
class ShoppingItem extends Component {
render() {
const { authenticated } = this.props.user;
const { name, createdAt, classes, id } = this.props;
const deleteButton = authenticated ? (
<DeleteItem id={id} />
) : null;
return (
<Card className={classes.card}>
<CardContent>
<Typography variant="body1" color="textPrimary">
{this.props.id}
</Typography>
<Typography variant="body1" color="textPrimary">
{name}
</Typography>
{deleteButton}
<Typography color="textSecondary">
{dayjs(createdAt).format("h:mm a, MMM DD YYYY")}
</Typography>
</CardContent>
</Card>
);
}
}
ShoppingItem.propTypes = {
name: PropTypes.string.isRequired,
};
const mapStateToProps = state => ({
user: state.user
});
const actionsToProps = {
deleteItem
};
export default connect(
mapStateToProps,
actionsToProps
)(withStyles(styles)(ShoppingItem));
GET_ITEMSeach time you post item and show what's going on!handleSubmit = event => { event.preventDefault(); const newItem = { name: this.state.name, handler: this.props.user.user.name }; this.props.postItem(newItem); this.props.getItems(); };