Help with search filter on Vue Axios

I’m building an app to consume a json and list it with a search filter input and other stuff.

I’ve already tried to create the function but it didn’t work.

CodeSandBox URL : https://codesandbox.io/s/vue-template-x1l1t?fontsize=14

The items arent shown. If I change the condition v-for=“produtos in produtoFiltrado” for v-for"produtos in gc.produtos" it works but not filtered as I wish

because at the first moment gc is just {} and doesn’t contain produtos, but in produtoFiltrado you try to this.gc.produtos.filter(...) that causes an error.
You can do something like if (!this.gc.produtos) return 'loading or whatever or []'.

Hey, @valq7711 ! Thank you for replying.
I’m new in Vue, could you please be more specific?
I think you can edit the code in CodeSandBox.

I’d be grateful <3

it seems that axios doesn’t work at CodeSandBox (always rejects with empty error)
try this:

produtoFiltrado: function() {
      if (!this.gc.produtos) return []; 
      return this.gc.produtos.filter(cust => {
        return cust.nome.match(this.search);
      });

Its running but nothing happens…

is there something in the console?

Nope, there’s no error…

there is no produtos in gc, it is an array

// set gc to null in data
{ gc: null, 
...
}

//and try this 
produtoFiltrado: function() {
      if (!this.gc) return []; 
      return this.gc.filter(cust => {
        return cust.nome.match(this.search);
      });

Yes, maybe the error is on our data, not in function.
How can I fix it?

Now its showing this error : “TypeError: this.gc.filter is not a function”

could you update codeSandBox?

Sure, there is:

You doesn’t fix data - set gc to null initially (it is common practice), not to {}

gc: null

Like this?

Just updated

stills the same

like this

return {
      gc: null,

Still not working

updated code:

I need to load all items before

Two issues.

  1. Codesandbox is on the https protocol, therefore your endpoint call must also be otherwise you’ll get security errors.
  2. match is intended to be used with a regexp. It will be converted if just a string is passed, however I believe by default the match is case sensitive. Also, it returns an array so you’d have to deal with that.

A simple solution is to use includes and convert the strings being tested against to lower case. Perhaps not the most elegant solution, but if that’s all you need, then it’s simple and concise.

Edit:

In fact, this might be more suitable if you prefer the flexibility of Regex.

produtoFiltrado: function() {
  if (!this.search) return this.gc;

  let regex = (new RegExp(this.search, 'i'));
  return this.gc.filter(cust => regex.test(cust.nome));
}

Still not working, James :worried:

Forgot to save my Codesandbox, but yes, it definitely works.

Oh, its really working!
But, I need to show all the items on page load. How can I?