Mapping arrays from objects using Next.js and Typescript

I am trying to create a mapping for the object below using { ...product.images[0] }, { ...product.type[0] }, and

{ ...product.productPackages[0] }
in my code snippet.

This is the object I need to map:

export const customImage = [
  {
    status: false,
    image: null,
    price: 10,
  },
];

I have imported it like this:

import { customImage } from "@/utils/customImage";

The current declaration seems incorrect. I received an error for this mapping [specifically for

selectedCustomImage: customImage,
]. The error message is:

Type '{ status: boolean; image: null; price: number; }[]' is missing the following properties from type 'SelectedCustomImageType': status, image, pricets(2739)
(property) selectedCustomImage: SelectedCustomImageType

Any assistance on mapping this array correctly would be greatly appreciated.

Here's a snippet of my code :

"use client";
import { useCart } from "@/hooks/useCart";
import { customImage } from "@/utils/customImage";
import { formatPrice } from "@/utils/formatprice";
import { Rating } from "@mui/material";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
import { MdCheckCircle } from "react-icons/md";
import toast from "react-hot-toast";
import Button from "@/app/components/Button";
import CustomImageInput from "@/app/components/inputs/CustomImageInput";
import PackageButton from "@/app/components/inputs/PackageButton";
import ProductImage from "@/app/components/products/ProductImage";
import SetQuantity from "@/app/components/products/SetQuantity";
import TypeImage from "@/app/components/products/TypeImage";
import SetColor from "@/app/components/products/setColor";
import SetType from "@/app/components/products/setType";

interface ProductDetailsProps {
  product: any;
}

export type CartProductType = {
  id: string;
  name: string;
  description: string;
  category: string;
  brand: string;
  selectedImg: SelectedImgType;
  selectedProduct: SelectedProductType;
  quantity: number;
  selectedPackage: SelectedPackageType;
  price: number;
  productPrice: number;
  file: any;
  selectedCustomImage: SelectedCustomImageType;
};
// customImagePrice: number;

export type SelectedImgType = {
  color: string;
  colorCode: string;
  image: string;
};

export type SelectedProductType = {
  type: string;
  typeCode: string;
  typePrice: number;
  image: string;
};

export type SelectedPackageType = {
  packaging: string;
  price: number;
  image: string;
};

export type SelectedCustomImageType = {
  status: boolean;
  image: string;
  price: number;
};

export type CustomImage = {
  status: boolean;
  image: File | null;
  price: number;
};

const Horizontal = () => {
  return <hr className="w-[30% my-2]" />;
};

const ProductDetails: React.FC<ProductDetailsProps> = ({ product }) => {
  const router = useRouter();

  const { handleAddProductToCart, cartProducts } = useCart();

  const [isProductInCart, setIsProductInCart] = useState(false);

  const [cartProduct, setCartProduct] = useState<CartProductType>({
    id: product.id,
    name: product.name,
    description: product.description,
    category: product.category,
    brand: product.brand,
    selectedImg: { ...product.images[0] },
    selectedProduct: { ...product.type[0] },
    quantity: 1,
    price: product.price,
    productPrice: product.price,
    selectedPackage: { ...product.productPackages[0] },
    file: null,
    selectedCustomImage: customImage,
  });

  useEffect(() => {
    setIsProductInCart(false);

    if (cartProducts) {
      const existingIndex = cartProducts.findIndex(
        (item) => item.id === product.id,
      );

      if (existingIndex > -1) {
        setIsProductInCart(true);
      }
    }
  }, [cartProducts]);

  ...


export default ProductDetails;

Answer №1

Seems like the item you are trying to access should be in an array format, but it seems like you forgot to specify the index:

    selectedPackage: { ...product.productPackages[0] },
    file: null,
    selectedCustomImage: customImage[0],

Additionally, make sure to assign an empty string instead of null.

export const customImage = [
  {
    status: false,
    image: '',
    price: 10,
  },
];

If the object does not need to be in an array format, then remove the square brackets:

export const customImage =
  {
    status: false,
    image:'',
    price: 10,
  };

Finally, no need for the map call anymore

<div className="grid grid-cols-2 gap-3">
  <CustomImageInput
    item={customImage}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating or deleting multiple batches of entries in Firebase Realtime Database

I am currently utilizing Firebase real time database in the following way: createSoldLead(soldLead: SoldLeadModel): void { const soldLeadsReference = this.angularFireDatabase.list<SoldLeadModel>( `groups/${this.groupId}/soldLeads` ); ...

Tips for detecting users without any linked email when working with the session object in NextAuth utilizing the Prisma adapter

The app is built using NextJS 13 with the app router, Prisma for database querying, NextAuth for authentication, and Planetscale for database hosting. My goal is to retrieve user information from the session object and then use Prisma to query in an api r ...

I am sorry, but there seems to be an issue with the JSON input as it is ending

Whenever I try to submit the form in edit mode, I encounter two errors. An unexpected end of JSON occurred Input provided caused an unexpected end of JSON The update process works perfectly fine and successfully saves values in the database. However, I ...

Understanding Typescript typings and npm packages can greatly improve your development workflow

I'm pleased to see that NPM has now included support for importing TypeScript type wrappers. However, I've noticed inconsistency in how these wrappers are maintained. For instance, when attempting to import "node-git" and "@types/node-git", I fou ...

Is it possible to schedule deployments using Vercel Deploy Hooks in Next.js?

When we schedule a pipeline on git, I want to schedule deploy hooks on vercel as well. Since the app is sending getStaticProps and every HTTP request will be run on every build, I have to rebuild the site to get new results from the server. For instance, ...

Utilizing the Next.js "Link" Element as a Personalized React Component Using Typescript

When attempting to utilize the "Link" element as a custom react component that I modified with typescript to enhance its functionality, I encountered a recurring issue in my project. Each time I used it, I had to include a property named props which contai ...

Troubleshooting: Difficulty with Angular 2 TypeScript interface array functionality

Currently, I am developing an Angular 2 application where I aim to showcase messages by utilizing an interface and storing all the messages in an array. Below is a snippet of my TypeScript component that highlights this functionality: export class ChatCom ...

How can I populate an array to use in a datatable when rendering?

How can I ensure that my datatable renders with the proper data on my webpage without needing to interact with the sort button? Where should I populate the array for use in a datatable so that it occurs before the rendering? export function MyComponent() ...

Exploring Computed Properties in Angular Models

We are currently in the process of developing an application that involves the following models: interface IEmployee{ firstName?: string; lastName?: string; } export class Employee implements IEmployee{ public firstName?: string; public l ...

Steps for modifying the value of a field within an Angular formGroup

Is there a way to update the value of the "send_diagnostic_data" field in a separate function? private generateForm(): void { this.messageForm = new FormGroup({ message: new FormControl(''), date: new FormControl(new Date()), messag ...

Tips for configuring the _document.tsx file in Next.js for optimal performance

I found most of the code for this project in the official documentation example on utilizing styled-components: https://github.com/vercel/next.js/blob/canary/examples/with-styled-components/pages/_document.js However, the example was written in .js and I ...

Error: Trying to access 'MaterialModule' before it has been initialized results in an uncaught ReferenceError

I have been working on a form for a personal project and attempted to implement a phone number input using this example: . However, after trying to integrate it into my project, I encountered an error. Even after removing the phone number input code, the e ...

What is the best way to fetch the data from this API?

function fetchCoinPrice(coinName) { return axios .get( `https://min-api.cryptocompare.com/data/pricemulti?fsyms=${coinName}&tsyms=EUR` ).then((response) => (response.data[coinName]["EUR"])); The JSON response for the coin "BTC" is: ...

Tips for effectively managing index positions within a dual ngFor loop in Angular

I'm working on a feedback form that includes multiple questions with the same set of multiple choice answers. Here's how I've set it up: options: string[] = ['Excellent', 'Fair', 'Good', 'Poor']; q ...

Tips on including a trash can symbol to rows in a bootstrap table using React

I am working on a table that contains various fields, and I want to add a trash icon to each row so that when it is clicked, the specific row is deleted. However, I am encountering an issue where the trash icon is not showing up on the row and I am unable ...

writeFileSync does not generate or add data to file

I currently have multiple SSG pages in my Next.js project and I am working on creating the navigation menu with various routes. I want to optimize this process by "caching" the first API call and retrieving the saved data from a file for subsequent request ...

Stripe-node does not return metadata when accessing a Checkout Session's line items

I have successfully set up a stripe checkout session where I am passing the products from the request's body in the line_items property. Each product in the product_data includes metadata with the product's id. try { const cart: ICart[] = ...

When utilizing TypeScript, is it possible to indicate a different type for a null argument when calling a function?

I was intrigued by the behavior in TypeScript where line A compiles successfully while line B does not. function someFunction<T>(arg: T): void { console.log(arg) } someFunction<string>('some string') // this works fine someFunction ...

Explain the object type that is returned when a function accepts either an array of object keys or an object filled with string values

I've written a function called getParameters that can take either an array of parameter names or an object as input. The purpose of this function is to fetch parameter values based on the provided parameter names and return them in a key-value object ...

Guide on mocking a function inside another function imported from a module with TypeScript and Jest

I have a function inside the action directory that I want to test: import { Action, ActionProgress, ActionStatus, MagicLinkProgress } from '../../interfaces' import { areSameActions } from '../actionsProgress' export const findActionPr ...