Kevin Powell - CommunityKP-C
Kevin Powell - Communityโ€ข2mo agoโ€ข
12 replies
thethingisback

Conditional return ref-timing issue (React)

My <ImgScrollGallery/> component has 3 local states; canScrollLeft, canScrollRight (both null by default), and invImagesMap (empty obj {} by default).

The component receives as an arg, model_imgs_key.
The return tests Object.keys(invImagesMap).length, and since it's still 0 upon first mounting, returns the first version of FadeTransition;
<FadeTransition key="loading" className="gallery_root"/> (see 2nd attmt).

My first useEffect, the one listening for the model_imgs_key argument, runs a
fetch
call with it, and saves the response to the thusfar empty object local state invImagesMap, populating it.

2 things react to the invImagesMap state assignment;
1. The return is changed to now instead display the second FadeTransition:
<FadeTransition key="content" className="gallery_root" ref={scrollContainerRef}> (see 3rd attmt)
2. The second useEffect (the one listening for invImagesMap[model_imgs_key]) is triggered to run.

This second useEffect needs to be able to define a scrollContainer variable, by referencing the ref assignment made on the second, latter
<FadeTransition ref={scrollContainerRef}/> container, in order to subsequently set the canScrollLeft & canScrollRight states, which the <LeftScrollBtnLarge/> & <RightScrollBtnLarge/> buttons inside of this latter FadeTransition depend on to render. (see attmt 4 for how 2nd version of <FadeTransition/> should look).

However, this 2nd useEffect can't define scrollContainer (using the ref) because the second/latter <FadeTransition ref={scrollContainerRef}/> is not fully mounting in time, thus scrollContainerRef.current doesn't yet have a value able to be read, and so those states (which control the buttons' returns) are being left null. The second/latter <FadeTransition ref={scrollContainerRef}/> container renders, but lacks the <RightScrollBtnLarge/> since canScrollRight is unable to be set

GH in comment
Was this page helpful?