0

//i need to add objects into a array using reducer for contact book

//reducer

const addContact = (contacts = [], action) => {
  let contactsArr = [{}];
  if (action.type = "ADD_CONTACT") {
    return [...contactsArr, action.payload];
  }
  return contacts;
};

actions

export const addContactRed = contact => {
  return {
    type: "ADD_CONTACT",
    payload: contact
  };
};


{
type:"ADD_CONTACT",
payload:{name:"xyz",phonenum:10101001}
}

{
type:"ADD_CONTACT",
payload:{name:"abc",phonenum:0101001}
}

//after dispatching two actions final array i want is

//contactsArr

[
{name:"xyz",phonenum:10101001},
{name:"abc",phonenum:0101001}
]

3
  • 4
    This line if (action.type = "ADD_CONTACT") { seems to be wrong. This is not doing comparison but assigning the value Commented Apr 15, 2019 at 16:25
  • 1
    your first code block will always add an empty object to the reducers state Commented Apr 15, 2019 at 16:28
  • yes, it is wrong it should be if(action.type==="ADD_CONTACT"). Thanks ... Commented Apr 15, 2019 at 16:34

1 Answer 1

1

You don't have ton init let contactsArr = [{}]; It will reset the store value in your reducer. Just use the contact store variable

const addContact = (contacts = [], action) => {
 // if (action.type = "ADD_CONTACT") {
  if (action.type === "ADD_CONTACT") {
    return [...contacts, action.payload];
  }
  return contacts;
};
Sign up to request clarification or add additional context in comments.

Comments

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.