Pierre Torres
Pierre Torres

Reputation: 287

UseEffect does not load at the right time Reactjs

Hello I have created a modal component, in order to display the details of one of my products from a list in my database. So I get the id that I send back to firebase.

My concern is that since it's a modal, it makes useEffect to the loading of my main component and not the opening of the modal, so the id is asked before the opening of the modal and so it doesn't know it.

I would like to do useEffect only when I open my modal.

Do you have an idea? Thank you very much.

export function ProjetDetails({showModalPD, setshowModalPD, id, setid}) { 



const [orders, setOrders] = useState([]);
const [type, setType] = useState('');

var IdProjet = id;

console.log(IdProjet);



useEffect( () => {
              fire
              .firestore()
              .collection("orders")
              .doc(id)
              .get()
              .then((doc) => {
                setType(doc.get("type"));
                
              });

              console.log(IdProjet);
}, []);

Upvotes: 0

Views: 50

Answers (1)

delis
delis

Reputation: 594

When you call useEffect, you can specify what changes in dependencies trigger it (second argument).

You are currently using [] meaning it would only be triggered once.

If you had a properly configured linter (with exhaustive-deps), it would have complained that a dependency id isn't passed in as the second argument to useEfect even though it is used in the hook .doc(id)

try changing to

useEffect( () => {
  if (!id) return;

  fire
    .firestore()
    .collection("orders")
    .doc(id)
    .get()
    .then((doc) => {
       setType(doc.get("type"));
    });

  console.log(IdProjet);
}, [id]);

If you also want firebase to be called whenever you open the modal, you can add that as a dependency (}, [id, showModalPD]);) to firebase. You wouldn't want to call firebase when it changes to false so can add a check for that too.

When anything in your dependency for useEffect changes, it would be called again.

Upvotes: 2

Related Questions