search

Home  >  Q&A  >  body text

How to initialize a hook with data that can only be accessed after mounting?

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粉801904089P粉801904089269 days ago395

reply all(1)I'll reply

  • P粉432930081

    P粉4329300812024-02-18 00:50:24

    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}){
     //...
    }
    

    reply
    0
  • Cancelreply