Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I make a variable in the updated object for my setter function?

I am mapping over an object and each key should have a button to set its value to null. I have it working for a single key but I need it to be a variable for each item in the map.

const Football = () => {
  const [team, setTeam] = useState({
    qb: null,
    te: null,
    rb: null,
    wr: null,
    flex: null,
  });

  return (
    <div>
      <h5>My Team</h5>
      {Object.keys(team).map((positionKey) => (
        <div key={positionKey}>
          {positionKey.toUpperCase()}: {team[positionKey]?.name}{" "}
          <button onClick={() => setTeam({ ...team, qb: null })}>
            Remove {positionKey} From Team
          </button>
        </div>
      ))}
    </div>
  );
};

I want the qb key in setTeam to be the variable positionKey from the map. If I put positionKey in directly it makes a new key in the team object called positionKey.

setTeam({ ...team, qb: null })

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use [positionKey] instead of a fixed value

onClick={() => setTeam({ ...team, [positionKey]: null })}

see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading