T
T
TuMko2021-11-20 11:38:06
JavaScript
TuMko, 2021-11-20 11:38:06

Why is undefined flying into the function parameter of a Vue 3 component?

Good afternoon. I have a Vue component. We get an array of data from the server into the certificate variable. The received certain fields of the certificate must be converted (only numbers should be left in the lines). The shortingTechItems function is written for this. When I throw the certificate.pto value into it, it gives the error "Cannot read properties of undefined (reading 'map')", i.e. in the function itself, undefined arrives in item. In another similar component, the same function works without errors (maybe it's the amount of data received from the API, in another component there are fewer of them, so they load faster). What is the problem and how to fix it?

<td class="border w-50 px-2 text-center">
   {{ shortingTechItems(certificate.pto) }}
</td>


export default {
  setup() {
    const route = useRoute();
    const store = useStore();
    const certificate = ref({});

    onMounted(async () => {
      certificate.value = await store.dispatch(
        "certificate/loadById",
        route.params.id
      );
    });

    const shortingTechItems = (item) => {
      const arr = [];
      item.map((i) => {
        arr.push(Number(i.replace(/\D+/g, "")));
      });
      return arr;
    };

    return {
      certificate,
      shortingTechItems,
    };
  },
};

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Tash1moto, 2021-11-20
@Tash1moto

add a check for existence
since the method is called before the data is loaded

<td v-if="certificate.pto" class="border w-50 px-2 text-center">
   {{ shortingTechItems(certificate.pto) }}
</td>

0
0xD34F, 2021-11-20
@0xD34F

const certificate = ref({});

shortingTechItems(certificate.pto)

arrives undefined

This is a fucking surprise - we try to read the value of a non-existent property from the object and get ... we get ... Aaaaaaaaaaa!!!!!!111
What is the problem

In zero knowledge of js.
how to fix?

In general - to master js.
Well, right now you can set the default value for the property passed to the function in the form of an empty array. Or you can check inside the function what came if not an array - don't try to use this thing as an array.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question