[Vuejs]-Vue3 how do I make this hook reactive

4👍

Since you said this is simplified i will treat it as a complicated thing you have 3 methods

Use ComputedRef

More info: https://vuejs.org/guide/essentials/computed.html#basic-example

export const useOpeningHours = (
  flight: Ref<FlightOption | null>,
  identifier: string,
  isEnabled?: boolean
) => {
    return {
      show: computed(() => {
        if (flight.value) return false
        return true
      }),
      gate: computed(() => {...}),
    }
}

This returns show and gate is a ComputerRef it’s the same as show.value

If you use @vueuse/core you have an easier way

export const useOpeningHours = (
  flight: Ref<FlightOption | null>,
  identifier: string,
  isEnabled?: boolean
) => {
  return toReactive(computed(() => {
    if (!flight.value) {
      return {
        show: false,
        gate: "",
      };
    }

    return {
      show: ...,
      gate: ...
    } 
  }))
}


const flight = ref<FlightOption | null>(null);

const { show: showOpeningHours } = toRefs(useOpeningHours(
  flight,
  props.identifier,
  true
));

use Reactive

export const useOpeningHours = (
  flight: Ref<FlightOption | null>,
  identifier: string,
  isEnabled?: boolean
) => {
  const result = reactive({ <default value> })

  watchEffect(() => { // or watch, watchPostEffect, watchSyncEffect
    if (!flight.value) {
      result.show = false
      result.gate = ""
    }
    ...
  })

  return result
}


const flight = ref<FlightOption | null>(null);

const { show: showOpeningHours } = toRefs(useOpeningHours(
  flight,
  props.identifier,
  true
));

use Ref

export const useOpeningHours = (
  flight: Ref<FlightOption | null>,
  identifier: string,
  isEnabled?: boolean
) => {
  const show = ref(false)
  const gate = ref("")

  watch(flight, flight => { // or watchEffect
    if (!flight) {
      show.value = false
      gate.value = ""
    }

    ...
  }, { immediate: true })

  return { show, gate }
}

0👍

Try to use a computed property as follows :

export const useOpeningHours = (flight: Ref<FlightOption | null>, identifier: string, isEnabled?: boolean) => {
  const details = computed(() => {
    if (!flight.value) {
      return {
        show: false,
        gate: "",
      };
    } else {
      return {
        show: true,
        gate: "GATE 1",
      };
    }
  });

    return {
        details
    };
};

and use it like :

const { details } = toRefs(useOpeningHours(
  flight,
  props.identifier,
  true
));

//then use `details.value.show` or `details.value.gate`

Leave a comment