Home > OS >  Having promise response inside Vue template interpolation
Having promise response inside Vue template interpolation

Time:08-18

I'm using Vue 2 and the composition API. My current component receives a prop from a parent and I render different data based on it, on the screen - the prop is called "result" and is of type Object, containing multiple info. I receive one "result" at a time, but multiple will be rendered - you can think of my "result" as a google search result - which means that the page will have multiple results.

The issue I have is that for one of the info inside "result", I need to call an asynchronous method and display its result, which is what I cannot accomplish.

Currently this is what I have:

<div>
   {{ getBoardName(props.result.boardReference) }}
</div>

Method inside the script:

async function getBoardName(boardReference) {
  var result = await entriesApi.getBoardName({
    boardReference: boardReference,
  });
  return result;
}

It displays "[object Promise]", although if I console.log(result) right before returning it, it's just what I need, so it seems to me as if the interpolation doesn't actually wait for the promise result.

I've also tried using "then" inside the interpolation:

{{
  getBoardName(props.result.boardReference).then((value) => {
    return value;
   })
}}

I was thinking about using a computed property but I am not sure how that would work, as the response I need from the method has to be connected to each result individually.

Please ask for further clarifications if needed.

CodePudding user response:

As you thought, the interpolation does not actually wait for the result so this is why you have a Promise object.

Since you are using the composition API, what you can actually do is to use a reactive state (using the ref() function if you are waiting for a primitive type, which seems to be the case here, or the reactive() function for objects) and update the state within the onMounted() lifecycle hook.

setup(props, context) {
  const boardGameName = ref("");

  onMounted(async () => {
    boardGameName.value = await getBoardName(props.result.boardReference);
  });

  async function getBoardName(boardReference) {
    var result = await entriesApi.getBoardName({
      boardReference: boardReference,
    });
    return result;
  }

  return {
    boardGameName,
  };
}

Since you are dealing with async data, you could add a loading state so you can show a spinner or something else until the data is available.
If your board reference changes over time, you could use a watcher to update your board game name.

Good luck with your project!

  • Related