Reputation: 5566
I have a section in which users can change data using input on change, now I want to be able to delete items from the redux state.
Here is the code sand box link : live demo
Reducer
const initialState = {
firstName: "Kunta ",
lastName: "Kinte",
age: 35,
country: "Ghana",
IQ: 200
};
const DetailsReducer = (state = initialState, action) => {
const { name, value } = action;
return { ...state, [name]: value };
};
export default DetailsReducer;
Here is How I display data and tried to delete the first name but nothing happens
import { useSelector } from "react-redux";
const Details = () => {
const details = useSelector((state) => state);
const handleDelete = () => {
details.firstName = "";
};
return (
<div>
<h1> Details </h1>
<span> Firstname : {details.firstName}</span>
<button onClick={handleDelete}>Delete</button>
<br />
<span> LastName : {details.lastName}</span>
<button>Delete</button>
<br />
<span> age : {details.age}</span>
<button>Delete</button>
<br />
<span> country : {details.country}</span>
<button>Delete</button> <br />
</div>
);
};
export default Details;
What is the proper way to delete the item from a redux state like this?
Upvotes: 0
Views: 865
Reputation: 106
to change the redux state we need to use the useDispatch hook.
In your case:
import { useSelector, useDispatch } from "react-redux";
const Details = () => {
const details = useSelector((state) => state);
const dispatch = useDispatch();
const handleDelete = () => {
dispatch({
type: "change",
name: "firstName",
value: "",
});
}
...
You can use, in the reducer, the type property to add various behaviours to the redux state management.
Upvotes: 1