0

I have created this logic that when doing it's happy path, everything works fine. But when there is an error, I want to display it on the interface. My code looks like this (trimmed):

export function initCamera() {
  const loaded = ref(false);
  const cameras = ref([]);
  const error = ref(null);

  someTask().then((response) => {
      cameras.value = response;
  loaded.value = true;
    })
    .catch((error) => {
      console.log("we got an error", error);
  loaded.value = true;
      error.value = error;
      console.log(error.value);
    });

  return { loaded, cameras, error };
}

If there are no errors, then the interface does have access to the cameras and the loaded flag is set to true. If there is an error, it does set the loaded flag, but the error is always null.

All the console logs you see there display a value. My component looks like this:

export default defineComponent({
  name: "TheScanner",
  directives: {
    content,
  },
  emits: ["onExpand"],
  setup() {
    let init = false;
    const result = reactive({ loaded: Boolean, cameras: null, error: null });
    const expanded = ref(false);
    const instance = getCurrentInstance();

    const expand = (value: boolean) => {
      expanded.value = value;
      instance.proxy.$emit("onExpand", value);
    };

    watch(
      () => expanded.value,
      (value) => {
        if (!value || init) return;
        init = true;
        Object.assign(result, initCamera());
        console.log(result);
      }
    );

    return { expanded, expand, ...toRefs(result) };
  },
});

As you can see, I have setup the result as a reactive property and use Object.assign to assign my response to it. That console log there will show the cameras and loaded boolean values, but never shows the error. It's always null.

Does anyone know why?

1 Answer 1

1

Change the variable name 'error' into someting else, because you have declared another variable named 'error' above, the ref. In catch block, the variable 'error' points the error object, not the ref.

export function initCamera() {
  const loaded = ref(false);
  const cameras = ref([]);
  const error = ref(null);

  someTask().then((response) => {
    cameras.value = response;
    loaded.value = true;
  })
  // Pay attention to this line
  .catch((err) => {
   console.log("we got an error", err);
   loaded.value = true;
   error.value = err;
   console.log(error.value);
  });

  return { loaded, cameras, error };
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.