-1

I have a problem trying to update an Array of Objects that lives in a Themecontext, my problem is with mutation, I'm using Update from Immutability helpers. the thing is that when I update my array in my specific element, This appears at the end of my object.

This is my code:

function changeValueOfReference(id, ref, newValue) {

        const namevalue = ref === 'colors.primary' ? newValue : '#'; 
        console.warn(id);

        const data = editor;
        const commentIndex = data.findIndex(function(c) { 
          return c.id === id; 
        });

        const updatedComment = update(data[commentIndex], {styles: { value: {$set: namevalue} } })

      
        var newData = update(data, {
          $splice: [[commentIndex, 1, updatedComment]]
        });

        setEditor(newData);

this is my result:

enter image description here

NOTE: before I tried to implement the following code, but this mutates the final array and break down my test:

 setEditor( prevState => (
          prevState.map( propStyle => propStyle.styles.map( eachItem => eachItem.ref === ref ? {...eachItem, value: namevalue}: eachItem ))
        ))
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Codasko
  • 31
  • 5

1 Answers1

0

Well, I finally understood the issue:

1 - commentIndex always referenced to 0

The solution that worked fine for me:

1 - Find the index for the Parent

2 - Find the index for the child

3 - Add an array []

styles : { value: {$set: namevalue} }  => styles :[ { value: [{$set: namevalue}] } ]

Any other approach is Wellcome

Complete Code :

function changeValueOfReference(id, referenceName, newValue) {
    const data = [...editor];
      const elemIndex = data.findIndex((res) => res.id === id);
      const indexItems = data
        .filter((res) => res.id === id)
        .map((re) => re.styles.findIndex((fil) => fil.ref === referenceName));
      const updateItem = update(data[elemIndex], {
        styles: {
          [indexItems]: {
            value: { $set: namevalue },
            variableref: { $set: [''] },
          },
        },
      });
      const newData = update(data, {
        $splice: [[elemIndex, 1, updateItem]],
      });

      setEditor(newData);
}
Codasko
  • 31
  • 5