Search code examples
reactjsreact-hooksuse-effectreact-domuse-ref

Value of useRef is undefined inside the useEffect function


According to the documentation of useEffect, it starts after the HTML elements are rendered so why I am getting the value of useRef hook as undefined inside the useEffect function. How can I set the value of Input field using useEffect in this code.

  const territoryName = useRef();
  const [isLoading, setIsLoading] = useState(true);
  const [isDisabled, setIsDisabled] = useState(false);
  const [selectedColor, setSelectedColor] = useState("");
  const history = useHistory();
  const homepageRoute = useRouteLink("");

  const appContext = useContext(APP_CONTEXT);
  const { user, regionData, areaData, editId, displayedMap, existingPolygons } = appContext;



  useEffect(() => {
    if (!user.name || !regionData.length) {
      return history.push(homepageRoute);
    }
    else if (!areaData[editId]) {
      return errorToast("Invalid Region");
    }
    locateRegion(displayedMap, JSON.parse(areaData[editId]?.polygonVertices));
    setSelectedColor(areaData[editId]?.colorCode);
    territoryName?.current?.setValue(areaData[editId]?.mapName);
    console.log(territoryName.current) // Prints undefined
    setIsLoading(false);
  }, []);

return (
    <>
      <ToastContainer autoClose={3000} />
      <Sidebar isLoading={isLoading} isDisabled={isDisabled}>
        <SidebarHeader headerText={"Edit Territory"} showBackIcon />
        <HorizontalLine />
        <div className="modifypage-sidebar">
          <SidebarContent>
            <Input
              name="territory-name"
              ref={territoryName}
              id="territory-name"
              placeholder="Enter Territory Name"
              label="Territory Name"
            />
            <ColorPallet
              // selectedColor={selectedColor} onColorChange={onColorChange}
            />
          </SidebarContent>
          <HorizontalLine />
        </ div>

        <SidebarFooter
          text="Save"
          help="Save Changes"
          // handler={() => { updateArea(oldValues, territoryName.current.getValue(), selectedColor) }}
        />
      </Sidebar>
    </>
  )

Solution

  • The useRef might be undefined when the useEffect callback is run first, therefore a solution could be to listen for changes in the ref, check if it's defined, and only then continue with the function.

    More info on possible solutions can be found here