0

I have a menu list which has a list of items. I have a button "Order this" attached to each item. To prevent a user ordering the same menu multiple times (yes, they are not supposed to order more than one...) I want to set a boolean variable for each item. When they click "Order this", the boolean changes to true and the button changes to a text "menu ordered".

My initial attempt was to use an EnvironmentObject var:

class MenuState: ObservableObject {
@Published var items = [MenuItem]()
var mstate: Bool = false }

However, when I do this, the boolean is not assigned to each item in the list. As a result, all items in the list change when clicked.

Assigning the variable in the menu struct seems to be the solution, but I have made the items using json, which is immutable.

So, how could I attach boolean var for each item when the items are created using json?

struct MenuItem: Codable, Equatable, Identifiable {
var id: UUID
var name: String}

[
{
    "id": "EF1CC5BB-4785-4D8E-AB98-5FA4E00B6A66",
    "name": "Dish",
    "items": [
        {
            "id": "36A7CC40-18C1-48E5-BCD8-3B42D43BEAEE",
            "name": "Stack-o-Pancakes",
        }]

1 Answers1

0

You should probably add your boolean as a transient property of each MenuItem - the way you have it, the mstate refers to the entire menu:

struct MenuItem: Codable, Equatable, Identifiable {
var id: UUID
var name: String
var isOrdered: Bool?
}

There are a few ways to add a property to MenuItem and prevent it from being decoded: I made isOrdered an optional in the code here, but a better solution would be manually decoding the MenuItem objects, like in this answer.

Another option would be to have an array or dictionary of Bool values on your MenuState, to associate Bool values to a specific MenuItem.

John Nimis
  • 586
  • 3
  • 15