Ref is undefined unless I wrap in createEffect, if, and setTimeout
I'm appending a ref to the end of an array. It's always undefined unless I do it like this:
createEffect(() => {
if (fetchedBookInfo.state === 'ready')
setTimeout(() => setAllParagraphs([...allParagraphs(), bookInfoRef]))
})
I'm happy it works I just don't understand why it only works like this. I got it working like this through trial and error. If I take away any one of the createEffect, if statement, or setTimeout it breaks because bookInfoRef is undefined. Again, no problem on my end but if anyone can provide some illumination on why this is I'd love to learn 🙂
2 Replies
Refs in jsx are only set before onMount/effects, so if you don't have an effect it makes sense that the ref would be undefined. As for the rest of your question, we can't answer that without seeing your JSX for the component. My guess, however, is that the element you are using the ref with is not created until the state becomes "ready" (perhaps it is wrapped in a Show for example)
cool so you're dead on about the Show. I created a parent div around the show and set the ref to it. Removed the createEffect and the if statement and it works fine now. What you said made a lot of sense with the element being referenced being blocked by a Show.