Next.js Discord

Discord Forum

NextJS Server & Client State managment error

Unanswered
Acorn-plum gall posted this in #help-forum
Open in Discord
Acorn-plum gallOP
I've made a simple counter app which stores count value in database, im using server action to fetch data from db and, it stores and update db on incrment but upon refresh it resets local + db data also and i cant figure out why

9 Replies

Acorn-plum gallOP
//useCounterStore.ts
import {create} from 'zustand'
import {persist} from 'zustand/middleware'
interface CounterState {
    count: number,
    setCount: (count: number) => void;
    increment: () => void;
    reset:()=>void
}

export const useCounterStore = create(
  persist<CounterState>(
    (set) => ({
      count: 0,
      setCount: (count: number) => set({ count }),
      increment: () => set((state) => ({ count: state.count + 1 })),
      reset: () => set({ count: 0 }),
    }),
    {
      name: 'counter-storage',
    }
  )
);
//Counter.tsx
"use client";
import { sendCounterToServer } from "@/ServerActions/send_counter_to_server";
import { useCounterStore } from "@/store/useCounterstore";
import React, { useEffect } from "react";

const Counter = ({ count_value }: { count_value: number }) => {
  const { count, setCount, increment } = useCounterStore();

  useEffect(() => {
    setCount(count_value);
  }, [count_value, setCount]);

  useEffect(() => {
    const handle = setTimeout(() => {
      if (count > 0) {
        sendCounterToServer(count);
      }
    }, 5000);
    return () => {
      clearTimeout(handle);
    };
  }, [count]);

  return (
    <div>
      <div></div>
      <div>
        <div>
          {count}
        </div>
        <div>
          <button
            onClick={increment}>
            +
          </button>
          <button>
            -
          </button>
        </div>
      </div>
    </div>
  );
};

export default Counter;
Sun bear
Your useCounterStore is always starting with zero as initial value. You should fetch the current value from the database here.

At the moment the useCounterStore will show zero on every refresh.

To prevent the immediatly jumping to 1 you can try:

onClick={() => increment()}
Acorn-plum gallOP
@Sun bear first step - im confused how i gonna call server action from client and set to count state
onClick={() => increment()} i made this change but it has no effect
Sun bear
Calling server action from clientside like that:

export default funcrion ClientComponent() {

const [count,setCount] = useState(0)

useEffect(() => {
const fetchData = async () => {
 const data = await serverAction()
setCount(data)
}
fetchData()
},[])

}
Acorn-plum gallOP
@Sun bear man idk how tf it worked after i remove some console log im not really sure what was wrong
ah i remove that on extra useEffect
  useEffect(() => {
    console.log("Server Value", count_value);
    setCount(count_value);
  }, [setCount, count_value]);