Ada
Ada

Reputation: 569

How do I trigger my redux function in my component

I have a form that is supposed to create a new user on submit. On handleCreate I need redux to trigger the addUser action and update the state thereby creating a new user but I don't seem to be calling the action correctly.

action.js

 const addUser = payload => ({
    payload,
    type: ADD_USER,
});

reducer.js

const addUsers = (items, newItem) => {
    const { id } = newItem;
    items[id] = newItem;
    return { ...items };
};

       case ADD_USER: {
            const { users } = state;
            const { payload: { item } } = action;
            return {
                ...state,
                isUpdated: true,
                users: addUsers(users, item),
            };
        }

The function to trigger the action in the component

    handleCreate = () => {
        const { form } = this.formRef.props;
        const { addUser } = this.props.actions;
        form.validateFields((error, values) => {
            if (error) {
                return error;
            }
            form.resetFields();
            const user = {
                age: values.age,
                birthday: values[DATE_PICKER].format('YYYY-MM-DD'),
                firstName: values.firstName,
                hobby: values.hobby,
                id: uuid(),
                lastName: values.lastName,
            };
            addUser(user);
        });
    };

Upvotes: 2

Views: 130

Answers (2)

Taki
Taki

Reputation: 17654

The problem you have is with destructuring the playload, const { payload: { item } } = action; expects the payload to have a key item

const action = {
  payload: {
    item: {
      a: "a",
      b: "b"
    }
  }
};

const {
  payload: { item }
} = action;

console.log(item)

replace const { payload: { item } } = action; in your reducer with

const { payload: item } = action;

Upvotes: 2

Maria
Maria

Reputation: 295

Looking at your actual project linked in the comments of the other answer, I found the source of your problem, your reducer for ADD_USER needs to be

    case ADD_USER: {
      const { users } = state;
      return {
        ...state,
        isUpdated: true,
        users: addUsers(users, action.payload)
      };
    }

Before when you had const { payload: { item } } = action; you were expecting the action object to be shaped

{
   type: WHATEVER_TYPE,
   payload: { item: user }
},

But the action actually looks like

{
   type: WHATEVER_TYPE,
   payload: user,
},

Upvotes: 2

Related Questions