Search code examples
javascriptreactjsreact-hooksuse-state

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

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