T.Demirer
T.Demirer

Reputation: 138

How can I assign an array as an attribute of object in React Native?

This is my Course model. A slot is a time interval. There is different slots for different courses. I will use these slots in an Appointment model, so the users can select a slot an make their appointments. I'm having trouble with storing time slots.

class Course {
  constructor(
    id,
    mentorId,
    categoryId,
    duration,
    title,
    imageUrl,
    description,
    slots
  ) {
    this.id = id;
    this.mentorId = mentorId;
    this.categoryId = categoryId;
    this.duration = duration;
    this.title = title;
    this.imageUrl = imageUrl;
    this.description = description;
    this.slots = slots;
  }

I need something like this:

class Course {
  constructor(
    id,
    mentorId,
    categoryId,
    duration,
    title,
    imageUrl,
    description,
    **slots[]**
  ) {
    this.id = id;
    this.mentorId = mentorId;
    this.categoryId = categoryId;
    this.duration = duration;
    this.title = title;
    this.imageUrl = imageUrl;
    this.description = description;
    this.slots = slots;
  }

How can I assign this array as object attribute? Or how can I store this slot attribute? Thanks for your help.

Upvotes: 1

Views: 59

Answers (1)

Mostav
Mostav

Reputation: 2612

You can use either a class or interface and put something like this:

class Slot {
  attribute_1: type_1;
  attribute_2: type_2;
  ....
} 

or

interface Slot {
  attribute_1: type_1;
  attribute_2: type_2;
  ....
} 

and then declare your slots array in course class as below:

class Course {
    id: any;
    mentorId: any;
    categoryId: any;
    duration: any;
    title: any;
    imageUrl: any;
    description: any;
    slots: Slot[]; // or slots: Array<Slot>;
    constructor(
        id: any,
        mentorId: any,
        categoryId: any,
        duration: any,
        title: any,
        imageUrl: any,
        description: any,
        slots: Slot[] // or slots: Array<Slot>;
    ) {
        this.id = id;
        this.mentorId = mentorId;
        this.categoryId = categoryId;
        this.duration = duration;
        this.title = title;
        this.imageUrl = imageUrl;
        this.description = description;
        this.slots = slots;
    }
}

I put any as type just for the sake of the example,so feel free to change the types of the properties.

you can also handle null by doing:

slots: Array<Slot> | null;

Upvotes: 1

Related Questions