Answer the question
In order to leave comments, you need to log in
How to correctly remove messages in react-redux & hook?
I'm trying to delete a message that comes in props. I use hooks and redux. For some reason, the splice method does not delete one message at a time, but all that I would have sent.
How to do it right?
const ProfilePost = (props) => {
let [editMode, setEditMode] = useState(false);
let [messages, setMessages] = useState([props.message]);
let [post, setStatePost] = useState([props.posts]);
useEffect(() => {
setMessages(messages);
}, [messages]);
const activateEditMode = () => {
setEditMode(true);
};
const deactivateEditMode = (messages) => {
setEditMode(false);
props.updateMessage(messages);
};
const onMessageChange = (e) => {
setMessages(e.currentTarget.value);
};
const deleteMode = () => {
props.deletePost()
}
return (
<div>
<div>
{post.map((element, i) => (
<div className={style.message} id={i}>
{!editMode && (
<div>
<div>
<span></span>
</div>
<div className={style.message_wrapper}>
<div>
<span className={style.field_message}>
{props.message}
</span>
<div>
<button onClick={activateEditMode}>
edit message
</button>
</div>
<div>
<button className={style.button_delete} onClick={() => deleteMode()}>
delete
</button>
</div>
</div>
</div>
</div>
)}
{editMode && (
<div>
<span></span>
<TextareaAutosize
className={style.field_edit}
onChange={onMessageChange}
value={props.message}
/>
<div>
<button onClick={deactivateEditMode}>
save
</button>
</div>
</div>
)}
</div>
))}
</div>
</div>
)
}
let mapStateToProps = state => {
return {
newPostText: state.profilePage.newPostText,
posts: state.profilePage.posts,
};
};
let mapDispatchToProps = dispatch => {
return {
updateMessage: (message) => {
let action = updateMessage(message);
dispatch(action);
},
deletePost: () => {
let action = deletePost();
dispatch(action);
},
};
};
const ProfilePostEdit = connect(
mapStateToProps,
mapDispatchToProps
)(ProfilePost);
const DELETE_POST = 'DELETE_POST'
let initialState = {
profile: null,
posts: []
}
const profileReducer = (state = initialState, action) => {
switch (action.type) {
case DELETE_POST: {
return { ...state, posts: state.posts.splice(0, 1)}
}
}
export const deletePost = (key) => ({type: DELETE_POST, key})
};
}
Answer the question
In order to leave comments, you need to log in
A bit unclear. Is this all the reducer code? If all - then you have it completely empty, you are trying to cut an element from an empty array.
export const deletePost = (key) => ({type: DELETE_POST, key})
switch (action.type) {
case DELETE_POST: {
// action.key = post_id который надо удалить
return {
...state,
posts: state.posts.filter(post => post.key !== action.key)
}
}
}
props.deletePost(айдиПоста)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question