1

i'm trying to work with swiftUI but i'm having an issue. i want to fetch the data from firebase and show that data to the list. i used mutating function to modify the variable. now when i called that function than it give me error. how i can solve this please help me. below are the code i'm using.

struct UserListView : View {


var body: some View{
    VStack{
        List{
            VStack(alignment:.leading){
                HStack{
                    Text("Favroute").frame(alignment: .leading).padding(.leading, 20)
                    Spacer()
                    Text("All").frame(alignment: .trailing)
                }
            ScrollView(.horizontal, content: {
                HStack(spacing: 10) {
                    ForEach(0..<10) { index in
                        StatusView(statusImage: "nature")
                    }
                }
                .padding(.leading, 10)
            })
                .frame(height: 190)
            }

            ForEach(0..<10){_ in
                HStack{
                    Group{
                        NavigationLink(destination: ChatView()){
                            UserImageView(imageName: "profileDummy").padding(.leading, 5)
                            Text("User Name").padding(.leading,10)
                        }
                    }
                }.frame( height: 40)
            }.environment(\.defaultMinListRowHeight, 40)
        }
    }
    .navigationBarTitle("UserList",displayMode: .inline)
    .onAppear {
        self.userList()
    }
}


var userDataList = [UserModel]()
mutating func userList() {
    databaseReference.child(DatabaseNode.Users.root.rawValue).observe(.value) { (snapShot) in
        if snapShot.exists(){

            if let friendsDictionary = snapShot.value{

                for each in friendsDictionary as! [String : AnyObject]{
                    print(each)
                    if let user = each.value as? [String : Any]{
                        let data = UserModel(userId: JSON(user["userId"] ?? "").stringValue, name: JSON(user["name"] ?? "").stringValue)
                        print(data)
                        self.userDataList.append(data)
                    }
                }
            }
        }
    }
}

}

below are the error message i'm getting:

Cannot use mutating member on immutable value: 'self' is immutable
Sourav Mishra
  • 501
  • 4
  • 21

1 Answers1

0

You should declare your userDataList property like so @State var userDataList = [UserModel](). This way this property will be stored by SwiftUI outside of your struct and can be mutated.

Natalia Panferova
  • 1,134
  • 7
  • 9