First of all, I am very new to React, so please excuse my ignorance. But I am really struggling to get a piece of code to work.
First of all, the premise is that I have an array of class objects, and I am trying to incorporate them into a dictionary, where the key is a text property from that class object, and the value is an array of those objects with the property matching that key.
The idea is so that when I render the page, I can group all of those objects based on the key value.
Hopefully, this will make sense in my illustration below.
Assume that I have a class, as follows:
export class MyClass {
type: string;
description: string;
// other class properties
}
And my react component receives a list of those objects:
export interface IMyComponentProps {
myClasses?: MyClass[];
}
export const MyComponent: FC<IMyComponentProps > = ({myClasses}) => {
...
}
The idea is that I want to end up with a dictionary, with each key as a unique 'type' value from each class in that list, and the value is the list of classes that have that particular type.
I have spent a long while trying to get it to work, with the code below the closest I have managed. However, it falls over when trying to render the page, with a generic error.
export const MyComponent: FC<IMyComponentProps > = ({myClasses}) => {
const myDictionary: {
[key: string]: MyClass[]
} = {};
const populateDictionary = (myClasses: MyClass[]) => {
myClasses.forEach(populateDictionaryItem);
};
const populateDictionaryItem(myClass: MyClass)
{
myDictionary[myClass.type].push(myClass);
}
useEffect(() => {
populateDictionary(myClasses);
}, [myClasses]);
return (
<div>
...
</div>
)
}
Based on what I have read and how Javascript handles arrays, that should work, but it doesn't, and I am wondering if anyone is able to see what I am doing incorrectly.
Could it be that I have to inspect the dictionary first to see if the key exists, and create an empty array before the push if it doesn't? I haven't managed to work out the syntax to achieve that.
Again, apologies for my lack of experience, there are probably a few things in the code above that I am not doing correctly.