trash-and-fire / lightweight-charts-react-wrapper

React wrapper for financial lightweight charts
Other
58 stars 5 forks source link

why ref.current is undefined in useEffect? #22

Closed ChaiGuangJie closed 3 weeks ago

ChaiGuangJie commented 3 weeks ago
屏幕截图 2024-06-06 024405
trash-and-fire commented 3 weeks ago

This is a fundamental limitation in the interaction between react and the chart library. The chart library requires a dom element for initialization, and I can only get it in the effects phase, so references are initialized only after the second render of the internal components. At the moment I haven't figured out how to get around this limitation.

As workaround you can use following code:

function Component() {
   const [ref, setRef] = useState(null);

   useEffect(() => {
       if (ref) console.log(ref);
   }, [ref]);

   return <Chart width={400} height={300} ref={setRef}/>
}

I'd like to know a little more about your case. Could you please explain what you are going to do with the ref in the effect.

ChaiGuangJie commented 3 weeks ago

Thanks. That's enough for me!