How to initialize a hook with data that can only be accessed after mounting?
P粉801904089
P粉801904089 2024-02-17 22:35:42
0
1
389

Here is an example of what I'm trying to do:

import { useRouter } from "next/router";

import { useCollection } from "react-firebase-hooks/firestore";
import { db } from "@/firebase/clientApp";
import { collection } from "firebase/firestore";

export default function Test(){
    const router = useRouter();
    const {id} = router.query
    const [data, dataLoading, dataError] = useCollection(collection(db, "drafts", id), {})

    return(
    <div>Hello!</div>
    )
}

As you can see, I use the value of id to initialize the useCollection hook. However, the id changes and is first undefined and then changes to the correct value. This makes the whole thing break down and the above doesn't even work in typescript. I need to initialize the useCollection hook after defining the id, which is only after the component is "installed". I tried putting useCollection(...) inside useEffect but it doesn't work.

P粉801904089
P粉801904089

reply all(1)
P粉432930081

Since you are using nextjs, you can leverage getServerSideProps to generate the id for your component as the initial prop, so it will always be defined:

export async function getServerSideProps({ params }) {
  const id = params.id;

  return {
    props: {
      id,
    },
  };
}

and you receive it as a prop from the component:

export default function Test({id}){
 //...
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!