Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ignore React Custom Hooks for cognitive complexity rule #3983

Closed
MR-BH opened this issue Jun 21, 2023 · 0 comments · Fixed by SonarSource/eslint-plugin-sonarjs#444
Closed

Comments

@MR-BH
Copy link

MR-BH commented Jun 21, 2023

Just like #2238 , we also Ignore React Custom Hooks for cognitive complexity rule.

function useStorageState<T>(key: string, options?: Options<T>) {
  let storage: Storage | undefined

  // https://github.com/alibaba/hooks/issues/800
  try {
    storage = getStorage()
  } catch (err) {
    console.error(err)
  }

  const serializer = (value: T) => {
    if (options?.serializer) {
      return options?.serializer(value)
    }
    return JSON.stringify(value)
  }

  const deserializer = (value: string) => {
    if (options?.deserializer) {
      return options?.deserializer(value)
    }
    return JSON.parse(value)
  }

  function getStoredValue() {
    try {
      const raw = storage?.getItem(key)
      if (raw) {
        return deserializer(raw)
      }
    } catch (e) {
      console.error(e)
    }
    if (isFunction(options?.defaultValue)) {
      return options?.defaultValue()
    }
    return options?.defaultValue
  }

  const [state, setState] = useState<T>(() => getStoredValue())

  useUpdateEffect(() => {
    setState(getStoredValue())
  }, [key])

  const updateState = (value: T | IFuncUpdater<T>) => {
    const currentState = isFunction(value) ? value(state) : value
    setState(currentState)

    if (isUndef(currentState)) {
      storage?.removeItem(key)
    } else {
      try {
        storage?.setItem(key, serializer(currentState))
      } catch (e) {
        console.error(e)
      }
    }
  }

  return [state, useMemoizedFn(updateState)] as const
} // total cognitive complexity = 19

some real world code link:
https://github.com/alibaba/hooks/blob/5da4cc4faac901d0f042961c6eaff3297fdf4f6c/packages/hooks/src/createUseStorageState/index.ts#LL22C9-L22C9 complexity=19

https://github.com/alibaba/hooks/blob/5da4cc4faac901d0f042961c6eaff3297fdf4f6c/packages/hooks/src/useFullscreen/index.ts#L21 complexity=47

https://github.com/alibaba/hooks/blob/5da4cc4faac901d0f042961c6eaff3297fdf4f6c/packages/hooks/src/useLongPress/index.ts#L21 complexity=37

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
1 participant