nextjs localStorage getItem

huangapple go评论56阅读模式
英文:

nextjs localStorage getItem

问题

以下是您要翻译的内容:

"after searching half a day I still not able to getItem from local storage.

the idea is to save some data to local storage and based on that I want to route a user in the Layout component. I am able to save to local storage and delete but not able to get data from it. I get error 'local storage not defined' or 'destroy is not a function'

I have 3 components save, delete and get. save and delete I execute after a client side api call, the get function I need to be working in the Layout as it is the top level for all routes.

I Need a bit help to the right direction please.

---Upadte

I found something that works

export const IsAuth = ()=>{
    const [auth, setAuth] = useState();
    useEffect(()=>{
        if(typeof windows === undefined) return;
        const item = localStorage.getItem('ltu');
        setAuth(!!item);
    },[]);
    return auth;
}

now my problem is I have not much understanding of nextjs. I used the Layout to create a theme template, I basically have only 3 pages that can be visited if not logged in and the rest one needs to be logged in. I get so many examples but it seems like I need to verify auth on every single page instead of being able to do this on root/layout level.

all examples I get are without the use of Layout and I am totally stuck.

I want a simple login system just with jwt and check if thats there to show pages."

(请注意,"IsAuth"组件中的代码块中的 "windows" 应为 "window")

英文:

after searching half a day I still not able to getItem from local storage.

the idea is to save some data to local storage and based on that I want to route a user in the Layout component. I am able to save to local storage and delete but not able to get data from it. I get error 'local storage not defined' or 'destroy is not a function'

I have 3 components save, delete and get. save and delete I execute after a client side api call, the get function I need to be working in the Layout as it is the top level for all routes.

I Need a bit help to the right direction please.

---Upadte

I found something that works

export const IsAuth = ()=>{
    const [auth, setAuth] = useState();
    useEffect(()=>{
        if(typeof windows === undefined) return;
        const item = localStorage.getItem('ltu');
        setAuth(!!item);
    },[]);
    return auth;
}

now my problem is I have not much understanding of nextjs. I used the Layout to create a theme template, I basically have only 3 pages that can be visited if not logged in and the rest one needs to be logged in. I get so many examples but it seems like I need to verify auth on every single page instead of being able to do this on root/layout level.

all examples I get are without the use of Layout and I am totally stuck.

I want a simple login system just with jwt and check if thats there to show pages.

答案1

得分: 0

我在布局模板中无法让 localStorage.getItem() 正常工作。

我的解决方案虽然可能不完美,但是。

_app.js 中,我使用 useState() 创建并通过布局传递给菜单,在菜单中使用 useEffect() 与 'use client',在 useEffect 中设置我需要的全局状态。

_app.js:

export default function App({ Component, pageProps }) {
  const [isAuth, setAuth] = useState()
  const [user, setUser] = useState()

  return (
    <Layout setAuth={setAuth} isAuth={isAuth} user={user} setUser={setUser}>
      <Component user={user} setUser={setUser} isAuth={isAuth} {...pageProps} />
    </Layout>
  )
}

Layout.js:

export default function Layout({ children, setAuth, isAuth, user, setUser }) {
  return (
    <>
      <Headd />
      <SideMenu setAuth={setAuth} isAuth={isAuth} user={user} setUser={setUser}/>
      <main>
        <div className="menu-spacer"></div>
        <content>
          {children}
        </content>
      </main>
    </>
  )
}

menu.js:

'use client';
const SideMenu = ({setAuth, isAuth, user, setUser}) => {
 useEffect(() => {
    if (typeof window === 'undefined') return;
    const item = localStorage.getItem('ltu');
    setAuth(!!item);
    if (item)
      setUser(JSON.parse(localStorage.getItem('Ud')))
  }, [router, router.isReady])
}
英文:

I could not get the localStorage.getItem() to work in the layout template.

My solution while maybe not perfect is.

In the _app.js I create useState() and pass those along to the menu trough the Layout, in in the menu useEffect() with 'use client' in the useEffect I set the state I need global.

_app.js:

export default function App({ Component, pageProps }) {
  const [isAuth, setAuth] = useState()
  const [user, setUser] = useState()

  return (
    &lt;Layout setAuth={setAuth} isAuth={isAuth} user={user} setUser={setUser}&gt;
      &lt;Component user={user} setUser={setUser} isAuth={isAuth} {...pageProps} /&gt;
    &lt;/Layout&gt;
  )
}

Layout.js:

export default function Layout({ children, setAuth, isAuth, user, setUser }) {
  return (
    &lt;&gt;
      &lt;Headd /&gt;
      &lt;SideMenu setAuth={setAuth} isAuth={isAuth} user={user} setUser={setUser}/&gt;
      &lt;main&gt;
        &lt;div className=&quot;menu-spacer&quot;&gt;&lt;/div&gt;
        &lt;content&gt;
          {children}
        &lt;/content&gt;
      &lt;/main&gt;
    &lt;/&gt;
  )
}

menu.js:

&#39;use client&#39;;
const SideMenu = ({setAuth, isAuth, user, setUser}) =&gt; {
 useEffect(() =&gt; {
    if (typeof windows === undefined) return;
    const item = localStorage.getItem(&#39;ltu&#39;);
    setAuth(!!item);
    if (item)
      setUser(JSON.parse(localStorage.getItem(&#39;Ud&#39;)))
  }, [router, router.isReady])
}

Now I can use the {isAuth, user,} on any page and component.

I am pretty sure this is not the right solution, but I could not find any other working solution and no one here yet posted a answer.

huangapple
  • 本文由 发表于 2023年2月18日 11:14:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75490956.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定