0

I'm trying to change the value of an object property nested in an array nested inside an object using useState.

State is set as follows:

  const [groupState, setGroupState] = useState({
    groupId: uuidv4(),
    content: [{ rowId: uuidv4(), field: '', from: '', to: '' }],
  });

I'm trying to change the value of the 'field' property. If I add an entire 'dummy' object with the required value in the required property then it works:

setGroupState({
  ...groupState,
  content: groupState.content.map((item) => {
    if (item.rowId === rowId) {
      return (item = { rowId: uuidv4(), field: value, from: '', to: '' });
    }
  }),
});

However, I need to just update the specific property value, not the whole object. My latest effort is the following:

setGroupState({
  ...groupState,
  content: groupState.content.map((item) => {
    if (item.rowId === rowId) {
      return (item.field = value);
    }
  }),
});

Which returns the error: "Cannot create property 'field' on string 'user'" - I'm doing somethign wrong but I can't work out what.

2 Answers 2

1

Try destructing your item object:

setGroupState({
  ...groupState,
  content: groupState.content.map((item) => ({
    ...item,
    field: item.rowId === rowId ? value : item.field,
  })),
});

// Without explicit return
setGroupState({
  ...groupState,
  content: groupState.content.map((item) => {
    return { ...item, field: item.rowId === rowId ? value : item.field };
  }),
});
Sign up to request clarification or add additional context in comments.

3 Comments

Close but no cigar, it works but when you add another row, the field values in previous rows disappear
Need to find a way of knocking out the else value in the ternary but again, a whole series of errors. %&&%$£! :-)
No one can guesses how your app works, we answer your specific questions with the information we have.
0

Okay, got it, thanks Dennis Vash - just needed a little change:

setGroupState({
  ...groupState,
  content: groupState.content.map((item) => ({
    ...item,
    field: item.rowId === rowId ? value : item.field,
  })),

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.