Search code examples
vue.jsvuex

Error in callback for watcher in Vue reading properties of null


Got this error in my console after saving data/s. I'm not familiar with watch in Vue. although its reading the value but on the v-model="selected it catches callback error from watch property.

Error in callback for watcher "selected": "TypeError: Cannot read properties of null(reading 'value')"

my component code:

<template>
  <v-select
    :items="project_types"
    item-text="description"
    item-value="id"
    v-model="selected"
    return-object
    :menu-props="{ bottom: true, offsetY: true }"
    append-icon="fas fa-chevron-down"
    placeholder="Type"
    outlined
    dense
  />
</template>

<script>
import {
  httpSuccessResponseLogger,
  httpErrorResponseLogger
} from "@/helpers/logger";

export default {
  name: "TypeDropdown",
  data: () => ({
    project_types: [],
    selected: null
  }),
  methods: {
    getProjectStatuses() {
      this.$api.get("providers/project-types")
        .then(response => {
          httpSuccessResponseLogger(response);

          this.project_types = this.$_.get(response, "data.result.project_types", []);

        })
        .catch(error => {
          httpErrorResponseLogger(error);
        })

    }
  },
  created() {
    this.getProjectStatuses();
  },
  watch: {
    selected(item) {
      console.log({valueOf: item.value})
      this.$store.commit("projects/SET_FILTER_TYPE", {
        type: item.value
      });
    }
  }
};
</script>

<style scoped></style>

and in my Vuex with the module:

export default {
  namespaced: true,
  state: {
    filter: {
      type: []
    }
  },
  getters: {},
  mutations: {
    SET_FILTER_TYPE: (state, { type }) => (state.filter.type = type)
  },
  actions: {

  }
};

hope you can help. The problem was this.$refs.form.reset(); and how to make my data equals to not empty or null values. as I removed this.$refs.form.reset(); it was working fine but there is a data in the form.


Solution

  • For some reasons, item will be set to null sometimes, and if u want to read any property (such as value) from null, it will show TypeError.

    ? stands for optional(ES2020), when u try to get property from null or undefined, it will not show error any more by adding ?.

    to see more about ?

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

    so:

    item.value

    change it to:

    item?.value