Home  >  Q&A  >  body text

So I want to update a specific value inside an array of objects, but it's not updating correctly

<p>So I try to copy the array and when it matches the memberId I update the selected value of the specific object. For a single member it is valid. However, assuming there are multiple members, it doesn't update correctly. </p> <pre class="brush:php;toolbar:false;">const updateGroupMembers = (memberId: string, optedRider: string, value: string) => { const updatedMembers = group?.memberDetails?.map((member) => member.memberId === memberId ? { ...member, [optedRider]: value } : member ); if (updatedMembers) { setGroup((prevGroup) => ({ ...prevGroup!, memberDetails: updatedMembers, })); } };</pre> <p><br /></p>
P粉842215006P粉842215006429 days ago426

reply all(1)I'll reply

  • P粉957723124

    P粉9577231242023-08-19 00:51:29

    You can do this:

    useEffect(() => {
        setGroup((prevGroup) => ({
          ...prevGroup!,
          memberDetails: updatedMembers,
      }));
      }, [updatedMembers])

    useEffect will run once updatedMembers is updated.

    reply
    0
  • Cancelreply