본문 바로가기
FrontEnd/Next.js

[Next.js] localstorage 에 데이터 저장할 때 나타나는 에러 ( server,client 불일치) -Zustand

by 위그든씨 2023. 8. 24.

참고 : https://velog.io/@shyuuuuni/Next.jszustand-SSR-Hydration-%EC%97%90%EB%9F%AC-Text-content-does-not-match-server-rendered-HTML,

https://github.com/pmndrs/zustand/issues/1145,

내가 어떤 데이터가 새로고침 되더라도 초기화 되지 않게 하기 위해 그것을 로컬 스토리지에 저장했음.

그래서 새로고침을 하더라도 데이터는 쭉 유지 되는데 콘솔 창 에러로 아래 같이 나옴.

warning: Text content did not match. Server: "0" Client: "2" app-index.js:31

Warning: An error occurred during hydration. The server HTML was replaced with client content in <#document>. on-recoverable-error.js:21

Uncaught Error: Text content does not match server-rendered HTML.

Uncaught Error: There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.

그래서 마운트 되기 전에는 아무 것도 리턴하지 않고 마운트 시에만 뜨게끔 변경해줬더니 해결 됨.

 

'use client';
import { useCart } from '@/hooks/useCart';
import { ShoppingBag } from 'lucide-react';
import { useRouter } from 'next/navigation';
import React, { useEffect, useState } from 'react';

const NavbarActions = () => {
    const router = useRouter();
    const { count } = useCart();
    const [isMounted, setIsMounted] = useState(false);
    useEffect(() => {
        setIsMounted(true);
    }, []);
    if (!isMounted) {
        return null;
    }
    return (
        <button
            onClick={() => {
                router.push('/cart');
            }}
            className="bg-black text-white px-3 py-1 rounded-full flex justify-center items-center space-x-2 hover:ring-2 hover:ring-offset-2 hover ring-black"
        >
            <ShoppingBag className="w-4 h-4 " />
            <div>{count}</div>
        </button>
    );
};

export default NavbarActions;