0

I have this div in html where I can fill the inputs and then save that recipe to an array. And I have a method for that. Besides of that, I have a search field and a computed function to search the recipes on the array. But after I added the recipe to the array, if I try to clear the input that I used to put the name of the recipe, the search method tell me that "Cannot read property toLowerCase of null". I can't understand why the object I pushed to the array is causing me problems in the model. Below is the code, I don't know if I explained myself very well.

<div v-show="show_add_receta">
            <p>
                <input type="text" placeholder="id..." v-model="new_receta.id">
            </p>
            <p>
                <input type="text" placeholder="nombre..." v-model="new_receta.nombre">
            </p>
            <p>
                <textarea type="text" placeholder="descripcion..." cols="30" rows="10" v-model="new_receta.descripcion"></textarea>
            </p>
            <p>
                <input type="text" placeholder="chef..." v-model="new_receta.chef">
            </p>
            <p>
                <input type="text" placeholder="ingredientes..." v-model="nuevo_ingrediente" @keyup.enter="AgregarIngrediente()">
            </p>

            <ul>
                <li v-for="ingrediente in new_receta.ingredientes" :key="ingrediente.id"> {{ ingrediente.nombre }} </li>
            </ul>
            <p>
                <button @click="AgregarReceta()">Guardar nueva receta</button>
            </p>
        </div>

and this is the code of the functions:

    var vm = new Vue({
  el: "#appReceta",
  data: {
    lista_recetas: [
      {
        "id": "001",
        "nombre": "Receta de Tarta de manzana sin azúcar",
        "descripcion": "Descorazona dos de las manzanas y pélalas. Trocea en cubos grandes y ponlos en una olla al fuego con la ramita de canela. Una vez hierva, baja un poco el fuego, tapa la olla y deja cocer entre 20-30 min o hasta que las manzanas estén tiernas.",
        "chef": "Isabel Rescalvo",
        "ingredientes": [
          {
            "id": "i001",
            "nombre": " 3 manzanas grandes",
          },
          {
            "id": "i002",
            "nombre": " 1 rama de canela",
          },
          {
            "id": "i003",
            "nombre": "1 plátano maduro",
          },
        ]
      },
      {
        "id": "002",
        "nombre": "Carlota de mango",
        "descripcion": "Corta la punta de los bizcochos de soletilla sin excederte y guárdala. Recuerda que también puedes hacer la receta de carlota de mango con galletas Marías.",
        "chef": "Isabel Rescalvo",
        "ingredientes": [
          {
            "id": "i004",
            "nombre": "175 gramos de azúcar",
          },
          {
            "id": "i005",
            "nombre": " 2 claras de huevo a temperatura ambiente",
          },
          {
            "id": "i006",
            "nombre": "400 gramos de nata para montar o crema de leche",
          },
          {
            "id": "i007",
            "nombre": "100 gramos de mango troceado",
          },
        ]
      },
      {
        "id": "003",
        "nombre": "Pie de parchita",
        "descripcion": "Tritura las galletas hasta hacerlas polvo en la licuadora o procesadora.",
        "chef": " Dani León.",
        "ingredientes": [
          {
            "id": "i008",
            "nombre": " 3 yemas de huevo",
          },
          {
            "id": "i009",
            "nombre": " 1 lata de leche condensada (397 grs)",
          },
        ]
      },
      {
        "id": "004",
        "nombre": "Dulce de leche reposteroa",
        "descripcion": "Tritura las galletas hasta hacerlas polvo en la licuadora o procesadora.",
        "chef": "Carolina. ",
        "ingredientes": [
          {
            "id": "i010",
            "nombre": " 1 litro de leche entera",
          },
          {
            "id": "i011",
            "nombre": "  300 gramos de azucar (1½ tazas)",
          },
          {
            "id": "i012",
            "nombre": " 1 cucharadita de esencia de vainilla",
          },
        ]
      },
      {
        "id": "005",
        "nombre": "Mermelada de nísperos",
        "descripcion": "Limpia los nísperos, quítales el hueso y la piel..",
        "chef": " Montse Morote Ortega",
        "ingredientes": [
          {
            "id": "i013",
            "nombre": "  1 kilogramo de nísperos sin piel y sin hueso",
          },
          {
            "id": "i014",
            "nombre": " 200 gramos de azúcar (1 taza)",
          },
          {
            "id": "i015",
            "nombre": "1 trozo de limón",
          },
          {
            "id": "i016",
            "nombre": "2 cucharadas soperas de agua",
          },
        ]
      },
    ],
    search: '',
    show_add_receta: false,
    new_receta:{
        "id": "",
        "nombre": "",
        "descripcion": "",
        "chef": "",
        "ingredientes": []
      },
    nuevo_ingrediente: '',
  },
  computed: {
    lista_recetas_filtrada: function () {
      var self = this
      return this.lista_recetas.filter(
        function (value) {
          return value.nombre.toLowerCase().includes(self.search.toLowerCase())
        }
      )
    }
  },
  methods: {
    AgregarIngrediente: function () {
      var new_date = new Date();
      var ingrediente = {
        "id": 'i1000' + new_date.getTime(),
        "nombre": this.nuevo_ingrediente,
      }

      this.new_receta.ingredientes.push(ingrediente);
      this.nuevo_ingrediente = null
    },
    AgregarReceta: function () {
      var receta = this.new_receta;
      this.lista_recetas.push(receta);
      this.new_receta.nombre = null;
      console.log("Agregada")
    }
  }
})
1
  • Where are you trying to clear the input? Commented Apr 10, 2021 at 1:47

1 Answer 1

1

I've added the resetForm method that will clear the form after data is pushed into the array demo

For the sake of simplicity I've added some inline style, show the form, and added the new method that will clear the form when data is pushed to the array. I've used the ES6 Object spread syntax to clone the object.

eg

let objClone = { ...obj }; // pass all key:value pairs from an object

The above snippet clone the obj.

<template>
  <div v-show="show_add_receta" style="padding-left: 2rem">
    <p>
      <input type="text" placeholder="id..." v-model="new_receta.id" />
    </p>
    <p>
      <input type="text" placeholder="nombre..." v-model="new_receta.nombre" />
    </p>
    <p>
      <textarea
        type="text"
        placeholder="descripcion..."
        cols="30"
        rows="10"
        v-model="new_receta.descripcion"
      ></textarea>
    </p>
    <p>
      <input type="text" placeholder="chef..." v-model="new_receta.chef" />
    </p>
    <p>
      <input
        type="text"
        placeholder="ingredientes..."
        v-model="nuevo_ingrediente"
        @keyup.enter="AgregarIngrediente()"
      />
    </p>

    <ul>
      <li v-for="ingrediente in new_receta.ingredientes" :key="ingrediente.id">
        {{ ingrediente.nombre }}
      </li>
    </ul>
    <p>
      <button @click="AgregarReceta()">Guardar nueva receta</button>
    </p>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      lista_recetas: [
        {
          id: "001",
          nombre: "Receta de Tarta de manzana sin azúcar",
          descripcion:
            "Descorazona dos de las manzanas y pélalas. Trocea en cubos grandes y ponlos en una olla al fuego con la ramita de canela. Una vez hierva, baja un poco el fuego, tapa la olla y deja cocer entre 20-30 min o hasta que las manzanas estén tiernas.",
          chef: "Isabel Rescalvo",
          ingredientes: [
            {
              id: "i001",
              nombre: " 3 manzanas grandes",
            },
            {
              id: "i002",
              nombre: " 1 rama de canela",
            },
            {
              id: "i003",
              nombre: "1 plátano maduro",
            },
          ],
        },
        {
          id: "002",
          nombre: "Carlota de mango",
          descripcion:
            "Corta la punta de los bizcochos de soletilla sin excederte y guárdala. Recuerda que también puedes hacer la receta de carlota de mango con galletas Marías.",
          chef: "Isabel Rescalvo",
          ingredientes: [
            {
              id: "i004",
              nombre: "175 gramos de azúcar",
            },
            {
              id: "i005",
              nombre: " 2 claras de huevo a temperatura ambiente",
            },
            {
              id: "i006",
              nombre: "400 gramos de nata para montar o crema de leche",
            },
            {
              id: "i007",
              nombre: "100 gramos de mango troceado",
            },
          ],
        },
        {
          id: "003",
          nombre: "Pie de parchita",
          descripcion:
            "Tritura las galletas hasta hacerlas polvo en la licuadora o procesadora.",
          chef: " Dani León.",
          ingredientes: [
            {
              id: "i008",
              nombre: " 3 yemas de huevo",
            },
            {
              id: "i009",
              nombre: " 1 lata de leche condensada (397 grs)",
            },
          ],
        },
        {
          id: "004",
          nombre: "Dulce de leche reposteroa",
          descripcion:
            "Tritura las galletas hasta hacerlas polvo en la licuadora o procesadora.",
          chef: "Carolina. ",
          ingredientes: [
            {
              id: "i010",
              nombre: " 1 litro de leche entera",
            },
            {
              id: "i011",
              nombre: "  300 gramos de azucar (1½ tazas)",
            },
            {
              id: "i012",
              nombre: " 1 cucharadita de esencia de vainilla",
            },
          ],
        },
        {
          id: "005",
          nombre: "Mermelada de nísperos",
          descripcion: "Limpia los nísperos, quítales el hueso y la piel..",
          chef: " Montse Morote Ortega",
          ingredientes: [
            {
              id: "i013",
              nombre: "  1 kilogramo de nísperos sin piel y sin hueso",
            },
            {
              id: "i014",
              nombre: " 200 gramos de azúcar (1 taza)",
            },
            {
              id: "i015",
              nombre: "1 trozo de limón",
            },
            {
              id: "i016",
              nombre: "2 cucharadas soperas de agua",
            },
          ],
        },
      ],
      search: "",
      show_add_receta: true,
      new_receta: {
        id: "",
        nombre: "",
        descripcion: "",
        chef: "",
        ingredientes: [],
      },
      nuevo_ingrediente: "",
    };
  },
  computed: {
    lista_recetas_filtrada: function () {
      var self = this;
      return this.lista_recetas.filter(function (value) {
        return value.nombre.toLowerCase().includes(self.search.toLowerCase());
      });
    },
  },
  methods: {
    AgregarIngrediente: function () {
      var new_date = new Date();
      var ingrediente = {
        id: "i1000" + new_date.getTime(),
        nombre: this.nuevo_ingrediente,
      };

      this.new_receta.ingredientes.push(ingrediente);
      this.nuevo_ingrediente = null;
    },
    resetForm() {
      this.new_receta.id = "";
      this.new_receta.nombre = "";
      this.new_receta.descripcion = "";
      this.new_receta.chef = "";
      this.new_receta.ingredientes = [];
    },
    AgregarReceta: function () {
      this.AgregarIngrediente();

      var receta = { ...this.new_receta };
      this.lista_recetas.push(receta);

      console.log(receta);
      console.log(this.lista_recetas);
      this.resetForm();
    },
  },
};
</script>

<style>
</style>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!! The answer was to clone the object. I was suffering, because even after I pushed the object to the array, If I wrote on the name field, it changed in the saved object, a little bit weird, but now I understand why.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.