0
<template>
    <div>
        <h1>{{ searchWord(rawString) }}</h1>
    </div>
</template>

<script>
import axios from 'axios';

export default {
    methods: {
        searchWord(rawString) {
            const splitRawString = rawString.match(/^(\w\w\w)\d/);
            if (splitRawString) {
                // If regex found a match
                return axios
                    .get(`https://www.url.com/path/${splitRawString[1]}`)
                    .then(response => {
                        return response.data;
                    })
                    .catch(error => error);
            }
        }
    }
};
</script>

In the example above, I'm trying to output the result of the axios promise.

Unfortunately, the content of the <h1> tag is: [object Promise]

If I use console.log(response.data); instead of return response.data, it works.

studio-pj
  • 689
  • 6
  • 19

1 Answers1

-1

That's because you need to have the .then on the function not inside the function. What is happening is the function doesn't complete execution and moves on since you did not use a .then after it. try this:

data: () => ({ something: null})
...
async searchWord(rawString) {
            const splitRawString = rawString.match(/^(\w\w\w)\d/);
            if (splitRawString) {
                // If regex found a match
                this.something =  await axios
                    .get(`https://www.url.com/path/${splitRawString[1]}`)

            }
        }
    }

Stick something in your template instead of the function itself.

Michael
  • 4,538
  • 5
  • 31
  • 58
  • Since `searchWord` is marked as `async` it … still returns a promise. This doesn't solve the problem. – Quentin Dec 24 '19 at 09:31
  • edited my answer, call the function when the search is invoked. – Michael Dec 24 '19 at 09:36
  • @Michael I don't want to assign the response data to the Vue data function. I want the response data right here: `{{ searchWord(rawString) }}`. As you can see `searchWord` takes a parameter. – studio-pj Dec 24 '19 at 09:58
  • then you would have to do inline `.then` which is not a great idea...why can't you just use a property and put that inline? – Michael Dec 24 '19 at 10:01