react-router icon indicating copy to clipboard operation
react-router copied to clipboard

[Feature]: why useNavigate can only used in the context of a <Router> component ?

Open Silvia813 opened this issue 4 years ago • 1 comments

What is the new or updated feature that you are suggesting?

export function useCurrentUser () {
  const [currentUser, setCurrentUserAction] = useRecoilState(currentUserState)
  const navigate = useNavigate()
  const orgId = useOrgId()

  const setCurrentUser = useCallback((selectInfo, changeUrlLocation = true) => {
    if (changeUrlLocation) {
      switch (selectInfo.key) {
        case OKR_TYPE.COMPANY:
          navigate(`/${orgId}/okr/${IClazz.ORG}/${orgId}`)
          // history.push(`/${orgId}/okr/${IClazz.ORG}/${orgId}`)
          break
        case OKR_TYPE.GROUP:
          navigate(`/${orgId}/okr/${IClazz.GROUP}/${selectInfo.subject}`)
          // history.push(`/${orgId}/okr/${IClazz.GROUP}/${selectInfo.subject}`)
          break
        default:
          navigate(`/${orgId}/okr/${IClazz.USER}/${selectInfo.subject}`)
          // history.push(`/${orgId}/okr/${IClazz.USER}/${selectInfo.subject}`)
          break
      }
    }
    setCurrentUserAction(selectInfo)
  }, [history, orgId, navigate])

  return {
    currentUser,
    setCurrentUser,
  }
}

Why should this feature be included?

I'm migrate from v5 to v6. In v5, I use history.push to link in this hook,

In v6, I use useNavigate to replace useHistory, but got Error

Uncaught Error: useNavigate() may be used only in the context of a component.

so how should I do to make it work like before ?

Silvia813 avatar Jan 11 '22 03:01 Silvia813

solved. It seems I have to wrap a <Route> outside the component.

Silvia813 avatar Jan 11 '22 04:01 Silvia813