bonlim
bonlim

Reputation: 193

setting state in functional component. (object in array that is in object)

  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.

Upvotes: 0

Views: 27

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371168

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
  )
});

Upvotes: 2

Related Questions