0

This is more a react question I think;

export function useData() {
    const [Data]: any = useContractCall({
        abi: myContractInterface,
        address: myContractAddress,
        method: "getAllData",
        args: [],
    }) ?? [];
    return Data;
}
let myData = useData();
<div>{myData ? myData.name : "no Data yet"}</div>

UseData() is called and the view is rendered when myData is propagated; but how could I use myData somewhere else in my logic? Tried with an async wrapper and await, didn't work.

I tried to use useEffect to listen on changes of myData and react, but useEffect is fired immediately and myData is null.

  let myData = useData();
  
  useEffect(() => {
    console.log("Fresh Data is here",myData);//rotten undefined, not fresh data
  }, [myData ])
 

Should I just use something like this? I mean it is working.. but

const x = useData();

(async() => {
    console.log("waiting for variable");
    while(!x) // define the condition as you like
        await new Promise(resolve => setTimeout(resolve, 1000));
    console.log("variable is defined",x);
})();
aminrd
  • 4,300
  • 4
  • 23
  • 45
Suisse
  • 3,467
  • 5
  • 36
  • 59

1 Answers1

0

it's hard to figure out whole the bunch of custom hooks calling each other. I have in the end some "last in the chain" hook does async request and after receiving response triggers re-render with new value in const x.

With this assumption, I want to say you don't need to

(async() => {
    console.log("waiting for variable");
    while(!x) // define the condition as you like
        await new Promise(resolve => setTimeout(resolve, 1000));
    console.log("variable is defined",x);
})();

right in the render logic. Moreover it will never work. const x = useData() will never changed during this specific render execution. It will/may be re-assigned only on next re-render run.

Instead you should return some rendering result as if it is there. And it will be - initially null(by your words), but later component will re-render with actual data in x:

const x = useData();

....
return <SomeComponent prop={x} />

Also you should also see that with your

useEffect(() => {
  console.log("Fresh Data is here",myData);
}, [myData])

As at first it prints null and later dumps actual data.

Once re-render does not happen as I described above - the issue is somewhere within your custom hooks. And you will need to debug that with debugger.

skyboyer
  • 22,209
  • 7
  • 57
  • 64