Home > other >  Concating inside a map React
Concating inside a map React

Time:10-29

I am trying to use concat inside a mapping function. In this code snipped you see my function which first checks if there are any chips in the chips array. If not, a chip is created. This part works fine. If there are chips and the ID of the chip matches the ID of my target, I only change the displayed text and don't create another chip. This is also fine, but I would expect, that if this isn't the case, that I would be able to concat another chip, but this doesn't work. I also get not errors and when I log the last part it shows that a chip gets added to the array.

Am I missing something really simple here ? I would like to provide more code, but my project has lots of imports and stuff which would make this a very long post. Thanks for any help :)

const onAddBtnClick = (e) => {
    setChipsActive(true);
    setChips(
      chips.length === 0
        ? chips.concat({
            key: chips.length,
            label: e.target.value.toUpperCase(),
            id: e.target.name,
          })
        : chips.map((obj) => {
            if (obj.id === e.target.name) {
              return { ...obj, label: e.target.value.toUpperCase() };
            } else {
              chips.concat({
                key: chips.length,
                label: e.target.value.toUpperCase(),
                id: e.target.name,
              });
            }
            return obj;
          }),
    );
  };

CodePudding user response:

The js function concat exists on arrays and can only be used with other arrays.

So to fix your issue I would recommend you wrap the object you're trying to concat with an array, like so

chips.concat([{
                key: chips.length,
                label: e.target.value.toUpperCase(),
                id: e.target.name,
              }]);

important to note that this only returns an array where both arrays are concatenated, if you want to push the object into an array i would use

chips.push({
                key: chips.length,
                label: e.target.value.toUpperCase(),
                id: e.target.name,
              });

instead.

CodePudding user response:

What solved the issue for me was to take the array manipulation outside of the mapping and write another condition for it like this:

const onAddBtnClick = (e) => {
   setChipsActive(true);
const obj = {
     key: chips.length,
     label: e.target.value.toUpperCase(),
     id: e.target.name,
   };
   const newChips = (prevChips) => [...prevChips, obj];
   const updateChips = chips.map((obj) => {
     if (obj.id === e.target.name) {
       return { ...obj, label: e.target.value.toUpperCase() };
     } else {
       return obj;
     }
   });
   const hasChip = chips.some((el) => el.id === e.target.name);
   if (!hasChip) {
     setChips(newChips);
   } else {
     setChips(updateChips);
   }```
  • Related