0
  const [post, setPost] = useState({
    title: '',
    rolepair: [{name: '', job: ''}],
    industry: '',
    due_at: '',
    content: '',
  });

If I want to set data into post.rolepair[0].name, How could I do? I tried

setPost({...post, rolepair[0].source : newData});
setPost({...post, rolepair: post.rolepair[0].source(newData)});
setPost({...post, rolepair[0]: sorce : newData});

non of them worked though.

1 Answer 1

2

Map the rolepair property to a new array, and at the first index, add a new name property with the conditional operator:

setPost({
  ...post,
  rolepair: post.rolepair.map(
    (obj, i) => i === 0
      ? { ...obj, name: newData }
      : obj
  )
});
Sign up to request clarification or add additional context in comments.

3 Comments

what is :obj at the end for?
cond ? expr1 : expr2 is the conditional operator. It evaluates to expr1 if cond is truthy. Otherwise it evaluates to expr2.
ohhh oh my god.. I got it Thank you!!

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.