Search code examples
javascriptreactjsreactstrap

Can I use the variables declared in useEffect inside of my render in reactstrap?


I have a useEffect hook in my navbar:

  const spoon = localStorage.getItem("true");

  useEffect(() => {
    console.log(spoon")
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open('GET', `https://server.com/${spoon}`, false);
    xmlHttp.setRequestHeader('AO', `Password ${PASS}`)
    xmlHttp.send()
    console.log(xmlHttp.response)
    var data = JSON.parse(xmlHttp.response);
    console.log(data["user"]["avatar"]) 
    }, []);

Now when the user logs in, I trigger a request within the navbar to retrieve the users avatar, however, I only want to do this once so I use useEffect as if I do not, navigating between pages becomes slow as each click to take the user to a new page triggers another http get request in the navbar.

Now the useEffect does work, except now I believe am unable to use the data variable outside the scope(?) which means that in the navbar render I am unable to render the users avatar. Is there a way around this? Or am I able to use variables declared inside of useEffects in my render? Here is a snippet of my navbar render code:

return (
   ...
   <DropdownToggle
        caret
        color="default"
        nav
        onClick={(e) => e.preventDefault()}
        >
        <div className="photo">
        <img
         alt="..."
         src='{data["user"]["avatar"]}'  /*<-I need the data variable here so I can get the users avatar 
                                         from request*/
         />
         </div>
         <b className="caret d-none d-lg-block d-xl-block" />
         <p className="d-lg-none">Log out</p>
   </DropdownToggle>
)

Solution

  • You can't use variables from inside the useEffect within the render. If you want to use things from within the useEffect you have two options:

    1. Create state for the data i.e. useState however that will trigger a re-render, if that's what you want.
    2. Use a ref i.e. useRef() this can be used to have a variable that is persisted through out the renders. However changes to the ref will not trigger a re-render see: https://reactjs.org/docs/hooks-reference.html#useref

    Given you are using the data in a src you will have to use state to allow changes to data to re-render the component.