Alex
Alex

Reputation: 9720

using useRef Hook "element.current" is null inside useEffect Hook

const [data, setData] = useState<string>('');

let element = useRef(null);
let editor = useRef(null);

useEffect(() => {
    //fetch
    setData(fetchResult);
});

useEffect(() => {
    //element.current always is null
    if (element.current !== null) {
     editor.current = new JSONEditor(element.current, someOptions);
    }
}, [data, element]);

return (
<div>
        {loading && <CircularIndeterminateLoading />}
        {!loading && <div ref={element}></div>}
</div>)

element can be not null, but property .current is always null

any ideas how to solve?

Upvotes: 2

Views: 1499

Answers (2)

Hagai Harari
Hagai Harari

Reputation: 2877

You might use an isolated recursive function for making sure that there's some value under the ref

let handleEditor = () => element.current !== null ?
             editor.current = new JSONEditor(element.current, someOptions)
             : setTimeout(handleEditor, 50)

useEffect(() => {
    handleEditor()    
}, [data, element]);

Upvotes: 0

PsyGik
PsyGik

Reputation: 3675

You probably should add loading as a dependency in your useEffect because your ref is assigned only when the div is rendered, which in turn depends on the loading value.

By adding loading to the useEffect dependency, the ref will be available when the loading value changes.

useEffect(() => {
  if (element.current !== null) {
    editor.current = new JSONEditor(element.current, someOptions);
  }
}, [data, element, loading]);

return (
  <div>
    {loading && <CircularIndeterminateLoading />}
    {!loading && <div ref={element}></div>}
  </div>
);

Upvotes: 2

Related Questions