Initializing useState by modifying (mapping through) values of redux state

Viewed 30

I'm trying to initialize my state with the redux state that I have stored. However, when I try to map through one of the lists stored in the state it just resets the values that I have inside the list instead of returning their substring values (which I want). The thing is if I print mail.substring(0, mail.length -10) I see the value that I would like to assign to the variable but after assigning the value is empty.

Here comes the strange part: if I were to assign "hello" instead of mail.substring(0, mail.length-10) then it works which could make you assume that the substring would return an empty value but as I mentioned above it does not.

I guess this might be because I create a shallow copy of the redux state but I'm not sure. Could you help me resolve this, please?

const membershipData = useSelector(getCompanyMembershipDetails);

function getInitState() {
if (membershipData !== null && membershipData !== undefined) {
  const newState = { ...membershipData };
  newState.members.map((m) => {
    const mail = m.contact.countersignEmail;
    const newVal = mail.substring(0, mail.length - 10);
    m.contact.countersignEmail = newVal;
    return m;
  });
  return newState;
} else
  return {
    members: [getEmptyMemberStateForId(0), getEmptyMemberStateForId(1)],
    membershipRates: [
      getEmptyPropertyContributionForId(0),
      getEmptyPropertyContributionForId(1),
    ],
    registrationPermissions: [],
  };
}

const [membersData, setMembersData] = useState(getInitState());
1 Answers

It was because of the shallow copy as I thought. Using cloneDeep from lodash I made a working version:

const membershipData = useSelector(getCompanyMembershipDetails);

  function getInitState() {
    if (membershipData !== null && membershipData !== undefined) {
      const newState = _.cloneDeep(membershipData);
      newState.members.map((m) => {
        const mail = m.contact.countersignEmail;
        const newVal = mail.substring(0, mail.length - 10);
        m.contact.countersignEmail = newVal;
        return m;
      });
      return newState;
    } else
      return {
        members: [getEmptyMemberStateForId(0), getEmptyMemberStateForId(1)],
        membershipRates: [
          getEmptyPropertyContributionForId(0),
          getEmptyPropertyContributionForId(1),
        ],
        registrationPermissions: [],
      };
  }

  const [membersData, setMembersData] = useState(getInitState());

If you use lodash the way I did above make sure to import it the following way:

import _ from "lodash";
Related