Can we use action.payload on multiple object keys?

773 Views Asked by At

I want to add tasks to my Todo app with this action:

addTask: (state, action) => {
      const newTask = {
        id: uuidv4(),
        text: action.payload,
        completed: false,
        date: action.payload,
      };
      state.push(newTask);
    },

Which will be dispatched in this way to show both text and date:

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!inputFieldSlice || !dateSlice) return;

    dispatch(addTask(`${inputFieldSlice} on: ${dateSlice}`));

    dispatch(clearInputField(""));
    dispatch(clearDate(""));
  };

The output will be something like this: Shopping on: 2021-11-03

I wanted to know if this is the right way to do this and if I can actually pass action.payload to two different keys in an object.

1

There are 1 best solutions below

0
Zsolt Meszaros On BEST ANSWER

action.payload doesn't have to be a string. You don't even need to name it payload or action. You could simply pass an object as the payload with any keys you want. I chose text and date in this case:

addTask: (state, action) => {
  const newTask = {
    id: uuidv4(),
    text: action.payload.text,
    completed: false,
    date: action.payload.date,
  };
  state.push(newTask);
},

// ...

const handleSubmit = (e) => {
  e.preventDefault();
  if (!inputFieldSlice || !dateSlice) return;

  dispatch(
    addTask({
      text: inputFieldSlice,
      date: dateSlice,
    }),
  );

  dispatch(clearInputField(''));
  dispatch(clearDate(''));
};

By storing them separately, when you render the task, you can render it like this:

<ul>
  {tasks.map((task) => (
    <li key={task.id}>
      {task.text} on: {task.date}
    </li>
  ))}
</ul>