I'm new to TypeScript and I'm trying to gain experience by building small applications. I'm working on a form that will compile a list of game names and URL strings, with the ability for the user to add and remove additional entries. The logic for adding or removing an object from the array is working, but I'm having difficulty with the onChange handlers to handle dynamic values.
// interface for each game object
interface GameObj {
title: string;
steamUrl: string;
}
export const AddGameForm: React.FC<AddGameFormProps> = ({ ...props }) => {
// initial state
const [list, setList] = useState<GameObj[]>([{ title: '', steamUrl: '' }]);
.....
const handleTitleChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
const {
name,
value,
dataset: { id }
} = e.target;
console.log(name, value, id);
// use id prop to find the correct array object and update the title property
};
const handleURLChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const {
name,
value,
dataset: { id }
} = e.target;
console.log(name, value, id);
// use id prop to find the correct array object and update the steamUrl property
};
I have separate onChange handlers for the title and steamUrl properties and I've been able to access the data-id attributes, however I have not been able to use the id to update the correct object's property. I've tried to make a copy of the state, alter it and save it using the state setter, as well as attempt to use a callback function in the setter but I keep receiving TS errors such as 'Type 'undefined' cannot be used as an index type.' for the id. I have a working sandbox for this issue but I'm drawing a blank on how to proceed.