Search code examples
typescriptvue.jsvuejs3vue-composition-api

Vue 3 - Type 'Ref<boolean>' is not assignable to type 'boolean'


I have a custom hook, where I have a local state: But it seems, when i export the state with toRefs(), and use the state is another component, I get the error: "Type 'Ref' is not assignable to type 'boolean'"

The hook:

interface StateModel {
  isLoading: boolean;
  isError: boolean;
  errorMessage: string;
  data: object | null;
}

export default function useAxios(url: string, data: object) {
  const state: StateModel = reactive({
    isLoading: true,
    isError: false,
    errorMessage: '',
    data: null
  });

  const fetchData = async () => {
    try {
      const response = await axios({
        method: 'GET',
        url: url, // '/test_data/campaign.json'
        data: data
      });
      state.data = response.data;
    } catch (e) {
      state.isError = true;
      state.errorMessage = e.message;
    } finally {
      state.isLoading = false;
    }
  };

  return {
    ...toRefs(state),
    fetchData
  };
}

The component where im using the state and where I get the TS compile error:

setup() {
    const state: StateModel = reactive({
      data: null,
      isLoading: true
    });

    const { data, isLoading, fetchData } = useAxios(
      '/test_data/campaign.json',
      {}
    );

    const getCampaignData = async () => {
      await fetchData();
      state.data = data as CampaignModel;
      state.isLoading = isLoading; // ERROR HERE: Type 'Ref<boolean>' is not assignable to type 'boolean'
    };

    onMounted(() => {
      getCampaignData();
    });

    return {
      ...toRefs(state)
    };
  }

Why is it that the TS compiler is complaining? I've already defined in the Hook that it's a boolean?


Solution

  • You should get access to .value :

     state.isLoading = isLoading.value;
    

    since toRefs returns a ref