0

I have custom React hook which adding some scripts and add a variable to window object:

const useMyHook = ({ id, type }: Props) => {
  useScript('https:domain/main.js');
  useScript('https://domain/main2.js');

  useEffect(() => {
    window.mydata = { id: `${id}`, type: `${type}` };
  }, [id]);
};

I am using Apollo client and GraphQl for fetching data.

In my Page component, when I console.log(myData) the data returns undefined and then right after it returns the data (without refreshing). I am using Fragments.

From useQuery hook I can get the loading variable. How do I have to use loading and my custom hook so when loading === false -> use my custom hook.

I tried something like this:

const foo = useMyHook({ id: myData.id, type: myData.type });

Then below in the component in the return:

return (
 {!loading && foo}
 // Rest of the component jsx code
)

But still sometimes it returns first undefined?

How can I fix this issue?

# Update:

For now I added another prop loading: boolean and added this to the custom hook:

  useEffect(() => {
    if (!loading) {
      window.mydata = { id: `${id}`, type: `${type}` };
    }
  }, [id]);

Is this correct approach. And why does my fragment query first returns undefined?

meez
  • 3,783
  • 5
  • 37
  • 91

1 Answers1

0

You can add another prop like enabled for handling this issue

sth like this:

useMyHook.tsx :

const useMyHook = ({ id, type,enabled }: Props) => {
  useScript('https:domain/main.js');
  useScript('https://domain/main2.js');

  
  useEffect(() => {
    if(enabled)
    {
      window.mydata = { id: `${id}`, type: `${type}` };

    }
  }, [enabled]);
  

  
};

other component:

  const foo = useMyHook({ id: myData.id, type: myData.type,enabled:!loading && (data || error) });

  return foo

and you need to use data and error that can be deconstructed from useQuery (like loading ) to just make sure if loading is false and data or error exists (that's because of first time that the component renders, loading is false but and data and error doesn't exists because request is not submitted yet, that's why you see undefined first )

Ali Sattarzadeh
  • 3,220
  • 1
  • 6
  • 20