0

I am trying to use a Record<TableId, TableState> object where type TableId = string;. However, when I go to print out the contents of the record object after setting the key/value pair via setTableStateMap(map)... I get back the object {id: {…}} instead of the value I passed to the 'id' variable.

// App.tsx---------------------------------------
React.useEffect(() => {
    setCallback((id: TableId, tableState: TableState) => {
        const map: Record<TableId, TableState> = { id: tableState };
        setTableStateMap(map);
    });
    

// Table Component-------------------------------
type TableId = string;
type Callback = (id: TableId, state: TableState) => void;
let callback: Callback;
export function setCallback(callbackInput: Callback) {
    callback = callbackInput;
}

let stateMap: Record<TableId, TableState> = {};
export function setTableStateMap(map: Record<TableId, TableState>) {
    stateMap = map;
}

interface TableProps {
    id?: TableId;
}

export const Table: React.FC<TableProps> = ({
    id,
}) => {

    let tableState: TableState | undefined;
    if (id) {
        tableState = stateMap[id];
        // stateMap has key set to 'id' and not value of variable id
        // {id: {…}}
    } else {
        tableState = undefined;
    }
};
pilchard
  • 12,414
  • 5
  • 11
  • 23
  • Does this answer your question? [Add a property to a JavaScript object using a variable as the name?](https://stackoverflow.com/questions/695050/add-a-property-to-a-javascript-object-using-a-variable-as-the-name) – pilchard Aug 14 '23 at 22:52

1 Answers1

1

When you create an object using curly braces with a key like { id: tableState }, the string "id" is being interpreted as a static key, rather than the dynamic value of the id variable.You need to use computed property names in JavaScript/TypeScript. Computed property names allow you to use a dynamic value as the key when creating an object.

// App.tsx---------------------------------------
React.useEffect(() => {
    setCallback((id: TableId, tableState: TableState) => {
        const map: Record<TableId, TableState> = { [id]: tableState }; // Use computed property name here
        setTableStateMap(map);
    });

// Table Component-------------------------------
// ... your other imports and code

export const Table: React.FC<TableProps> = ({
    id,
}) => {
    let tableState: TableState | undefined;
    if (id) {
        tableState = stateMap[id]; // Now this will correctly access the value using the dynamic id
    } else {
        tableState = undefined;
    }
// ... rest of your component code
};
Nazrul Chowdhury
  • 1,483
  • 1
  • 5
  • 11