Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

getting the value of fetch inside useEffect without disturbing the events sequence

I have the following useEffect at start it sends a request to the sever then modify the state accordingly in this current implementation I want to manipulate the shared variable according do data yet I don’t want to put the rest of the logic inside the response block since the data show instantly and it brake my spinner logic any idea how to event this the right way , currently shared is undefined even if I am putting await before fetching ?

useEffect(() => {
    const getData = async () => {
      let shared = '';
      await fetch('/encrypt', {
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
        method: 'POST',
        body: JSON.stringify({ clientId: params[1] }),
      })
        .then((res) => {
          res.json().then((data) => {
          
          shared = data.data.split('_Shared_')[1];
          });
        })
        .catch((err) => {
          dispatch(SetSnackBarMsg({ bool: true, msg: 'Cannot get data.' }));
        });

      setLoading(true);
      dispatch(SetBackDrop(true));
      const docRef = doc(db, 'data-shared', shared);
      getDoc(docRef).then((docSnap) => {
        const data = docSnap.data();
        setLoaded(data?.img);
      });
      dispatch(SetBackDrop(false));
      setLoading(false);
    };
    getData();
  }, []);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here it is refactored to only use async/await:

useEffect(async () => {
    setLoading(true);
    const response = await fetch('/encrypt', {
    headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
    },
    method: 'POST',
    body: JSON.stringify({ clientId: params[1] }),
    })
    try {
      const data = await response.json();
    } catch(err) {
      dispatch(SetSnackBarMsg({ bool: true, msg: 'Cannot get data.' }));
    }
    const shared = data.data.split('_Shared_')[1];
    dispatch(SetBackDrop(true));
    const docRef = doc(db, 'data-shared', shared);
    const docSnap = await getDoc(docRef);
    setLoaded(docSnap.data?.img);
    dispatch(SetBackDrop(false));
    setLoading(false);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading