Search code examples
reactjsreduxredux-toolkit

Dispatching more than one payload


I'm struggling to understand why I can't dispatch more than one payload. In the code below, I want to dispatch "email" and "name", however only the first payload ("email") is going through:

dispatch(
  createAccount({ email: emailRef.current.value, name: nameUpdate() })
);

Below is the createSlice where the payload is received:

import { createSlice } from "@reduxjs/toolkit";
import { database, auth } from "../components/firebase-config";
import { ref, set } from "firebase/database";

const initialState = {
  value: 0,
};

export const counterSlice = createSlice({
  name: "posts",
  initialState,
  reducers: {
    createAccount: (state, action) => {
      const user = auth.currentUser;
      const uid = user.uid;

      set(ref(database, `users/${uid}`), {
        email: action.payload.email,
        name: action.payload.name,
      });
    },
  },
});

// Action creators are generated for each case reducer function
export const { createAccount } = counterSlice.actions;

export default counterSlice.reducer;

Solution

  • The action creators generated by Redux Toolkit's createSlice API only take a single argument as their payload by default. If you need to pass in multiple values, you must put them all inside an object, like dispatch(todoAdded({text: 'Buy Milk', completed: false})).

    Given that, the code that you've got looks valid atm. It would help if you could show what the nameUpdate function is, but I suspect that it's actually returning undefined or similar.