Search code examples
reactjsnext.jsclient-side

How to import a function in Next.js only on client side?


I am very new to Next.js, so pardon me for my mistakes. I have this function written using in axios that I only want to run on client side, since it used localstorage. Dynamic imports only work for components. Is there a way I could do that for just a function?


Solution

  • It sounds like you're doing the data fetching on the client side. You can execute this code in useEffect which will won't be executed until after the component is mounted.

    For example for client side fetch:

    useEffect(() => {
       const doMyAxiosCall = async () => {
            ...
    
            // Set localStorage values here
       }
    
       // This will only be executed on the client
       doMyAxiosCall();
    }, [])