ADR: best practice and code syntaxes - globe-and-citizen/cnc-portal GitHub Wiki

Checks for the CNC PR

For next PR, if one of the following checks is not met, the PR will be rejected. Eevry user is responsible to make sure that every files he edit respect the following rules. Even if this part of the code is note written by you or is not related to your feature.

Usage of Custom Fetch

Sometimes we have complex syntax that makes debugging difficult because we don't have access to the actual URL value that triggers the action. To solve this, we can use a reference to store the URL value and use it in the function.

Example of Complex Syntax

const {
  execute: executeSearchUser,
  response: searchUserResponse,
  data: users
} = useCustomFetch('user/search', {
  immediate: false,
  beforeFetch: async ({ options, url, cancel }) => {
    const params = new URLSearchParams()
    if (lastUpdatedInput.value === 'name' && searchUserName.value) {
      params.append('name', searchUserName.value)
    } else if (lastUpdatedInput.value === 'address' && searchUserAddress.value) {
      params.append('address', searchUserAddress.value)
    }
    // URL can be updated using a ref, so when the ref is updated the function will call 
    url += '?' + params.toString()
    return { options, url, cancel }
  }
})
  .get()
  .json()

Solution

const url = ref('user/search')

const updateURL = () => {
  const params = new URLSearchParams()
  if (lastUpdatedInput.value === 'name' && searchUserName.value) {
    params.append('name', searchUserName.value)
  } else if (lastUpdatedInput.value === 'address' && searchUserAddress.value) {
    params.append('address', searchUserAddress.value)
  }
  url.value += '?' + params.toString()
}

const handleUpdate = async () => {
  updateURL()
  await executeSearchUser()
}

const {
  execute: executeSearchUser,
  response: searchUserResponse,
  data: users
} = useCustomFetch(url)
  .get()
  .json()

With this you have a better control of the URL value and you can easily debug the URL value. In the same time the syntax is more clear and easy to read.

Usage of store

Calling a store with this syntaxt is not recommended. And it's not a good idea to use it like that in the function or in the template.

It's because, every time, the store will be called and the value will be updated. This can cause a lot of reactivity and can slow down the application.


import { useUserDataStore } from '@/stores/user'
const currentAddress = useUserDataStore().address as Address

The best we to use the store and keep the reactivity is


import { useUserDataStore } from '@/stores/user'
const userDataStore = useUserDataStore()

// the in the function or in the template you can call userDataStore.address