Search code examples
vuejs2vuejs3vue-composition-api

Vue2 Composition Api - How do I fetch data from api?


I am using Vue2.6 with composition api. I need to reroute to different pages depends on an api response. Can someone please guide me, please?

I tried using onBeforeMount but it renders the UI elements then rerouted to the corresponding page to the api response..so I can see a flash of the wrong UI..

setup() {
  const myData = 'myData';

  onBeforeMount(async () => {
    try {
        const results = await fetchData();
        // do reroute depends on results response
      }
    } catch (err) {
      console.log(err);
    }
  });

  return {
    myData,
  };

I also tried adding async in the setup method but it errored saying my ref variables "Property or method "myData" is not defined on the instance but referenced during render."

async setup() {
  const myData = 'myData';

  onMounted(async () => {
    try {
        const results = await fetchData();
        // do reroute depends on results response
      }
    } catch (err) {
      console.log(err);
    }
  });

  return {
    myData,
  };

Solution

  • It looks like you're trying to handle routing (re-routing) dynamically from inside a component. I can't see the rest of the apps, so can't speak to the validity of such a solution, but would like you dissuade you from doing that. routing logic should, IMO, not be handled in a component. The components should mostly just handle the template and user interaction. By the time you're rendering a component, that API should have been resolved already.

    I would recommend to resolve the API response before the route is even completed. You or use a navigationGuard to resolve the API during the route execution. This functionality is asynchronous, so you can await the response before proceeding.

    Alternatively, if you really want to handle it in the component, you will have that delay while the API is resolving, but you can implement some loader animation to improve the experience.