Home > Blockchain >  Uncaught (in promise) TypeError: obj.filter is not a function
Uncaught (in promise) TypeError: obj.filter is not a function

Time:12-23

<script setup> 
import { ref, onMounted, onBeforeMount ,reactive  ,computed} from 'vue';
import { useRoute } from 'vue-router';
import ApiService from '../../services/api.service';


const route = useRoute();  
const productId = route.params.productId; 
const products = ref([]);

const obj = reactive(products);
onMounted(() => {
    
    ApiService.getProduct().then((data) => (products.value = data));
  
});
const searchedProducts =computed( () => {
    obj.filter(product => productId.includes(product.productId))
    
  
});

console.log(searchedProducts);

</script>

<template>
    <p>datas {{searchedProducts}}</p>
</template>

onMounted to get all record and then computed searchedProducts fillter productId wise but {{searchedProducts}} not show i get error in console Uncaught (in promise) TypeError: obj.filter is not a function

CodePudding user response:

You may use it like this:

const obj = reactive({products});
...
const searchedProducts =computed( () => {
    return obj.products.filter(product => productId.includes(product.productId))
    
  
});

CodePudding user response:

The reason why your getting the error is that your wrapping a ref() inside of the reactive() without the usage of an object so you are need to add an .value to make it work like below. I made a StackBlitz to showcase.

const searchedProducts = computed(() => {
  return obj.value.filter((product) => {
    return product.id === productId;
  });
});`

But you probably intended to do it like the example below to make the ref() value unwrapped:

const obj = reactive({ products });

...

const searchedProducts = computed(() => {
  return obj.products.filter((product) => {
    return product.id === productId;
  });
});

Two other things to point out:

  1. You are using .includes() to compare products ids. A strict comparison would be more reliable to use.
  2. You forgot a return statement.
  • Related