0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

so I will need to do that for each field?
Yes, but it's possible add a more generic function, like: const handleDelete = (fieldName) => { dispatch({ type: "change", name: fieldName, value: "" }); and change the onClick events handler to a arrow function: <button onClick={() => handleDelete("firstName")}>Delete</button>. And, for example in other button: <button onClick={() => handleDelete("lastName")}>Delete</button>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.