javascript 如何使用firestore生成的id来创建slug

ddrv8njm  于 2023-03-21  发布在  Java
关注(0)|答案(1)|浏览(115)

我想知道如何使用新创建的firestore文档id来生成slug(title+id)。
在我的网站上,用户可以创建解决方案(文档),所以我想在生成解决方案时使用生成的解决方案的文档ID创建一个slug,然后在解决方案创建后将用户重定向到该slug。
下面是我的代码:

const StartCodingButton = ({ document, setIsOpen }) => {
  const { user } = useAuthContext()
  const { addDocument, response } = useFirestore("solutions")
  const { push } = useRouter()

  const { documents } = useCollection(
    "solutions",
    solutionDetails[0].challengeID
  )

  const initializeCodeEditor = async () => {
    if (documents.length > 0) {
      setIsOpen(false)
      push(`/playground/${documents[0].id}`)
    } else {
      const addedDocument = await addDocument({
        ...document,
        author:
          user.displayName !== null ? user.displayName : user.reloadUserInfo.screenName,
        userID: user.uid,
        slug: id+document.title // here I want to generate the slug
      })

      if (addedDocument) {
        setIsOpen(false)
        const id = addedDocument.id
        // redirect the user to the generated slug
        push(`/playground/${id}`)
      }
    }
  }

}
im9ewurl

im9ewurl1#

试试这个

slug: `${document.title}-${id}`.toLowerCase().replace(/[^a-z0-9]+/g, '-')

显然,你也可以将bottom函数改为:

if (addedDocument) {
        setIsOpen(false)
        push(`/playground/${addedDocument.slug}`)
}

相关问题