Unable to pass down returned value from one view to another

I have a Function addNote() that returns a value called 'idd' in the form of string

Now I have a view called ListView where there is a navigationLink that essentially needs that returned 'idd' value to be passed to this view called NoteView which is that navigationLink's destination. However I'm not able to pass that value down to NoteView.

I've been struggling with this for days now, I'd appreciate if someone could give me their two cents! Thanks a ton.

here’s the listview code:

` structure ListView: View {

@StateObject var dataManager = DataManager()
@State var isPresented = false

var body: some View {

    NavigationView {

        ZStack{
            
        List(dataManager.notes) { note in
            NavigationLink(destination: NoteView(newNote: note.content, idd: note.id)) {
                EmptyView()
           
                Text(note.content)}.buttonStyle(PlainButtonStyle())
            
        .frame(height: 0)
          

        .navigationTitle("Notes")
            
        .navigationBarItems(
            trailing: Button (action: {},
                              label: {
                
                NavigationLink(destination: NoteView(newNote: "", idd: "") )
                                      
      {Image(systemName: "plus")}
                  .simultaneousGesture(TapGesture().onEnded{
                      dataManager.addNote()
                  })}
                 ))
                .listStyle(.plain)
                .buttonStyle(PlainButtonStyle())     ‘

here’s the idd that addNote() returns:

`class DataManager : ObservableObject {

@Published var notes: [Note] = []
@Published var idd = ""

func addNote()-> String{
    let user = Auth.auth().currentUser
    let uid = Auth.auth().currentUser!.uid
    let db = Firestore.firestore()



    var ref: DocumentReference? = nil
    ref = db.collection("userslist").document(uid).collection("actualnotes").addDocument(data: ["content":"New Note"])

    {error in

    if let error = error{
        print(error.localizedDescription)
    }

        else {
                print("Document added with ID: \(ref!.documentID)")
          }

    }

    
  let  idd = ref!.documentID
    
     return idd

}`
  • Could you first reformat code (and use code formatter tool). As it is, it is very hard to understand, with random indentation and incomplete code. For instance, where does List { ends ?

  • hi @Claude31, so sorry for my ignorance. I just formatted the code properly and added that in one of the replies below. I couldn't edit the original post for some reason.

Add a Comment

Replies


//

//  ListView.swift

//  Notes10

//

//  Created by Mansidak Singh on 6/15/22.

//



import SwiftUI

import FirebaseFirestore

import Firebase

import FirebaseAuth



 

struct ListView: View {



    @StateObject var dataManager = DataManager()

    @State var isPresented = false



    var body: some View {



        NavigationView {



            ZStack{

                

            List(dataManager.notes) { note in

                NavigationLink(destination: NoteView(newNote: note.content, idd: note.id)) {

                    EmptyView()

               

                    Text(note.content)}.buttonStyle(PlainButtonStyle())

                

            .frame(height: 0)

              



            .navigationTitle("Notes")

                

            .navigationBarItems(

                trailing: Button (action: {},

                                  label: {

                    

                    NavigationLink(destination: NoteView(newNote: "", idd: "") )

                   

                       

          {Image(systemName: "plus")}

                      .simultaneousGesture(TapGesture().onEnded{

                          dataManager.addNote()

                      })}

                     ))

                    .listStyle(.plain)

                    .buttonStyle(PlainButtonStyle())

          

                

                

                

        }.environment(\.defaultMinListRowHeight, 55)

                .listStyle(.plain)

                .buttonStyle(PlainButtonStyle())

        .padding(.trailing, -80.0)

//

            }

        }.accentColor(.black)

    } }






Here is the Data Manager code that runs the addNote function


import Foundation

import FirebaseFirestore

import SwiftUI

import Firebase

import FirebaseDatabase

import FirebaseAuth









class DataManager : ObservableObject {

    

    @Published var notes: [Note] = []

    @Published var idd = ""





    func addNote()-> String{

        let user = Auth.auth().currentUser

        let uid = Auth.auth().currentUser!.uid

        let db = Firestore.firestore()







        var ref: DocumentReference? = nil

        ref = db.collection("userslist").document(uid).collection("actualnotes").addDocument(data: ["content":"New Note","time": [".sv": "timestamp"]])



        {error in



        if let error = error{

            print(error.localizedDescription)

        }



            else {

                    print("Document added with ID: \(ref!.documentID)")

              }



        }



//        @Binding var idd: String

        

      let  idd = ref!.documentID

        

         return idd

   

    }

    

    






Here is the NotesView code that accepts the idd




import Foundation

import SwiftUI



struct NoteView: View {



    

    @State var newNote: String = ""

    @State var idd: String = ""



@StateObject var dataManager = DataManager()



    var body: some View {

        TextEditor(text: $newNote)

        TextEditor(text: $idd)

   

            .padding(EdgeInsets(top: -10, leading: 10, bottom: 40, trailing: 0))

        

                      .font(.system(size: 16, design: .monospaced))

        

        



        Button (action: {

                

            dataManager.updateNote(idd: idd, noteContent: newNote)



                

            }, label: {Text("Update")}) .listStyle(.plain)

                    .buttonStyle(PlainButtonStyle())

    }

}


What is the specific problem you are having? What are you expecting to happen when you tap the Add button and what happens when you tap the Add button?

I looked at your code for the navigation bar items. The navigation link for the Add button passes an empty note to the note view with an empty ID before you have a chance to call addNote and get the new note's ID. You may have to create a new view for adding notes and show that when someone taps the Add button. Add the note when someone taps an Add button in the Add Note view.

Your DataManager class refers to a Note struct or class. Why do you have separate @State properties for the note contents and ID in the NoteView struct instead of a Note instance? Your addNote function could return the note instead of the ID. I think it would be easier to deal with notes than to deal with their individual pieces separately.

  • Thanks for the input, @szymczyk! So what you're saying is when someone clicks on the navigationLink I should first call the addNote function in dataManager and then pass the idd value I receive to a view called NewNoteView which is separate from NoteView. Am I getting it right?

  • @szymczyk if that's the case then I guess the question still remains how I would pass that idd value I receive from addNote() to the new NewNoteView?

  • Forget passing the idd. When someone taps the Add button, show a NewNoteView. The NewNoteView would have a button to add a note. When someone taps that button, create a new note and add it to the data manager's notes array.

    Why are you focusing so much on ids instead of notes? Is it something Firebase requires? You would have an easier time working with notes instead of ids.

    Please use replies instead of comments in the future. Apple sends notifications to me for replies but not comments.

Add a Comment