Search code examples
reactjstypescriptionic4

How to represent in typescript a list of objects where the key is the date and the content is an array?


I am racking my brain to represent the following data set in typescript: enter image description here

I'm trying as follows, but I get an error in ReactJs.

interface IDose {
  name: string;
  date: string;
}

interface IVaccine {
  [date: string]: IDose[]
}

const [data, setData] = useState<IVaccine[]>([]);

...

<IonGrid>
  <IonRow>
    {data.map((d, i) => {
      return (
        <IonCol key={i}>
          <IonButton>
            {d.date}
            <br />
            {d.name}
          </IonButton>
        </IonCol>
      );
    })}
  </IonRow>
</IonGrid>

Error: Uncaught TypeError: data.map is not a function...

Could anyone give me any suggestions?


Solution

  • I do see a few issues with your code.

    First and foremost, the data state does not seem to be an array of object, thus Array.map() won't work if you wish to iterate through the keys and print their respective values. Therefore, if you wish to iterate through data and print the values within it, you might want to use Object.values() instead. That being said, you should define the typings for state as an object (dictionary), rather than an array of objects.

    This are the changes you should make:

    interface IDose {
      name: string;
      date: string;
    }
    
    interface IVaccine {
      [date: string]: IDose[]
    }
    
    // here
    const [data, setData] = useState<IVaccine>();
    
    ...
    
    <IonGrid>
      <IonRow>
        // and here
        {data && Object.values(data).map((d, i) => {
          return (
            <IonCol key={i}>
              <IonButton>
                {d.date}
                <br />
                {d.name}
              </IonButton>
            </IonCol>
          );
        })}
      </IonRow>
    </IonGrid>