Home > Enterprise >  Save all items of an array to a Firestore array
Save all items of an array to a Firestore array

Time:02-03

This function saves data into Firestore.

static func createRecipe(docId:String, ingredientsAmount:Int, ingredientsName:String, completion: @escaping (Recipe?) -> Void) {
        
let db = Firestore.firestore()
        
        db.collection("recipes").document(docId).setData(
            [
             "title":title,
             "ingredients": [
                ["amount": ingredientsAmount,
                 "name": ingredientsName]
             ]
            ]) { (error) in
             }
    }

I'm using Codable to parse the data from an external source. But I have only been able to save one item at a time from the ingredients array.:

                do {
                    let decoder = JSONDecoder()
                    let recipe = try decoder.decode(Recipe.self, from: data!)

                    let uuid = UUID().uuidString
                    
                    createRecipe(
                        docId:uuid,
                        title: recipe.title ?? "",
                        ingredientsAmount: Int(recipe.ingredients?[0].amount ?? 0), // How to save EVERY item in recipe?
                        ingredientsName: recipe.ingredients?[0].name ?? "", // How to save EVERY item in recipe?
                    ) { recipeURL in
                        print("success")
                    }
                }
                catch {
                    print("Error parsing response data: \(error)")
                }

I can tell that I'm parsing the JSON data successfully because the following outputs every item in the ingredients array:

                    for eachIngredient in recipe.ingredients! {
                        print(eachIngredient.name)
                        print(eachIngredient.amount)
                    }

How can I save every item in the ingredients array to Firestore?

Any guidance is much appreciated!

CodePudding user response:

I'd suggest passing an array of Ingredients to the function and then using map to create the dictionaries:

static func createRecipe(docId:String, title: String, ingredients: [Ingredient], completion: @escaping (Recipe?) -> Void) {
    
    let db = Firestore.firestore()
    
    db.collection("recipes").document(docId).setData(
        [
            "title": title,
            "ingredients": ingredients.map { ["name": $0.name, "amount": $0.amount] }
        ])
        { (error) in
            //handle error
        }
}

Keep in mind that there's also a setData(from:) that takes a Codable, so since Recipe is Codable, you should just be able to do this (assuming recipe is a Recipe type):

try db.collection("recipes").document(docId).setData(from: recipe)

Documentation for the above function

  •  Tags:  
  • Related