Home > OS >  Hot to handle async props in vue 3 composition API
Hot to handle async props in vue 3 composition API

Time:11-21

Parent compoment:

const { getGroup, removePubli, removeTablet, loadTotal, error } = useGroups();
const group = ref({});
getGroup(group_id).then((g) => {
  group.value = g;
});

Child component:

const { group } = defineProps({
  group: {
    type: Object,
    default: {},
  },
});

Given the prop above, which is fetched by an async axios call, when I try to use it in a chield component it is undefined or a promise.

I've already tried to put an async inside onMounted hook but it doesn't work.

getGroup does it:

const getGroup = async (id) => {
  const r = await api.get(`/api/v1/groups/${id}`);
  if (r?.status !== 200) error.value = "Falhou";
  return r.data;
};

I want to await it before the code continues or find a way to do something when the promise resolves itself.

CodePudding user response:

I don't see in your code any await. Use await instead of .then!

<script setup>
const { getGroup, removePubli, removeTablet, loadTotal, error } = useGroups();

const group = ref({})

const result = await getGroup(someId)

group.value = result.data // or what ever
</script>

CodePudding user response:

Did you try to create a watcher in your child component and watch for group prop changes.

  • Related