Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to loop over mysql json field using prisma and typescript

I have a json field in mysql, and I am trying to loop over it.

I found that I should do this according to the Prisma docs:

  const Booking = await prisma.Booking.findUnique({
    where: { id: parseInt(params.id) },
  });

  let cateringObject: CateringItem[] | null = null;

  if (
    Booking?.catering &&
    typeof Booking?.catering === "object" &&
    Array.isArray(Booking?.catering)
  ) {
    const cateringObject = Booking?.catering as Prisma.JsonArray;
  }

I did try create this interface

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

interface CateringItem {
  quantity: number;
  productName: string;
  productPrice: number;
}

The error is when I try to loop over

          <ul>
            {cateringObject &&
              cateringObject.map((item) => <li>{item.productName}</li>)}
          </ul>

Property ‘map’ does not exist on type ‘never’.

>Solution :

 let cateringObject: CateringItem[] | null = null;
//
//
//
const cateringObject = Booking?.catering as Prisma.JsonArray;

Usually you cannot redeclare as a constant if you wish to use cateringObject outside the block. This might be what’s triggering the error as Typescript cannot infer the type of cateringObject.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading