简体   繁体   中英

How remove item from redux state using react hooks

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?

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM