Home > database >  How can I add an element to a list with a key value using a useState Record type in React typescript
How can I add an element to a list with a key value using a useState Record type in React typescript

Time:11-06

The structure of my Record type looks like this:

const PEOPLE_MAP_INIT: Record<string, Person[]> = {
        "1": [],
        "2": [],
        "3": []
    };

The useState is initialized like this:

const [PEOPLE_MAP, SET_PEOPLE_MAP] = useState<Record<string, Person[]>>(PEOPLE_MAP_INIT);

Basically, I am trying to hold a list of "Person objects" corresponding to the string key value which will each hold its own unique list.

I'm trying to add a Person object to the first list in the PEOPLE_MAP from a given master list of Person objects:

SET_PEOPLE_MAP({...PEOPLE_MAP, ["1"]: personList[i]});

However, this just gives me type errors. I know somewhere I'm misunderstanding the use of Record types but I'm just not sure how to go about fixing this.

CodePudding user response:

I wrote the AddPerson function like this and it works fine without any error type

const addPerson = () => {

  const newPerson = new Person('Joe', 30);

  const newPeopleMap = {...peopleMap};

  newPeopleMap["1"].push(newPerson);

  setPeopleMap(newPeopleMap);   
};

The whole code is here -> https://codesandbox.io/s/practical-wind-8spnv

  • Related