Skip to content

Instantly share code, notes, and snippets.

@bacarybruno
Created August 22, 2021 16:57
Show Gist options
  • Save bacarybruno/fbe3ec4df3c9346fbaf1ad9946764ae8 to your computer and use it in GitHub Desktop.
Save bacarybruno/fbe3ec4df3c9346fbaf1ad9946764ae8 to your computer and use it in GitHub Desktop.
import { ref, watch, onBeforeUnmount } from 'vue';
export const useState = (initialValue) => {
const state = ref(initialValue);
const setState = (value) => {
state.value = value;
};
return [state, setState];
};
export const useEffect = (callback = () => {}, deps = []) => {
let cleanup = () => {};
if (deps.length === 0) {
cleanup = callback();
}
deps.forEach((dep) => watch(dep, () => {
cleanup = callback();
}));
onBeforeUnmount(() => {
if (typeof cleanup === 'function') {
cleanup();
}
});
};
@bacarybruno
Copy link
Author

bacarybruno commented Aug 22, 2021

Example :

import dayjs from 'dayjs';
import localizedFormat from 'dayjs/plugin/localizedFormat';
import { useState, useEffect } from '@/composables/react-hooks';

dayjs.extend(localizedFormat);

export default function useCurrentDate() {
  const [currentDate, setCurrentDate] = useState(dayjs());
  const [formattedDate, setFormattedDate] = useState(dayjs());
  const [timer, setTimer] = useState(null);

  useEffect(() => {
    const timeout = setInterval(() => {
      setCurrentDate(currentDate.value.add(1, 'second'));
    }, 1000);
    setTimer(timeout);

    return () => {
      clearTimeout(timer.value);
    };
  }, []);

  useEffect(() => {
    setFormattedDate(
      currentDate.value.format('LL [at] LTS')
   	);
  }, [currentDate]);

  return { currentDate, formattedDate };
}

Bare VueJS

import {
  ref,
  computed,
  onMounted,
  onBeforeUnmount,
} from 'vue';
import dayjs from 'dayjs';
import localizedFormat from 'dayjs/plugin/localizedFormat';

dayjs.extend(localizedFormat);

export default function useCurrentDate() {
  const currentDate = ref(dayjs());
  const timeout = ref(0);

  onMounted(() => {
    timeout.value = setInterval(() => {
      currentDate.value = currentDate.value.add(1, 'second');
    }, 1000);
  });

  onBeforeUnmount(() => {
    clearInterval(timeout.value);
  });

  const formattedDate = computed(() => currentDate.value.format('LL [at] LTS'));

  return { currentDate, formattedDate };
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment