Next.js Discord

Discord Forum

Calling server action for only changed values of state

Unanswered
Polar bear posted this in #help-forum
Open in Discord
Polar bearOP
Hi. I have a state that is an array, let's call it questions, that gets updated by UI components on the client. I want to call a server function every time questions changes, but I only want to call the server function for the values of questions that have changed since the last re-render. I've tried storing the previous value of questions in another state and comparing that against the new value, but it doesn't seem to be accurately reflecting the previous value of questions before it was changed.

My code:
  const [questions, changeQuestion] =
    useState(data);
  const [lastQuestion, changeLastQuestion] = useState(data)
  useEffect(() => {
    async function updateDb() {
      questions.forEach(async (q, i) => {
        if (JSON.stringify(q) !== JSON.stringify(lastPq[i])) {
          await updateData(q); // server function
          changeLastQuestion([...pastQuestions]) // "last questions updated"
        }
      });
    }
    updateDb();
  }, [questions]);

2 Replies

Asian black bear
This sounds like premature optimization. Start with a regular PUT request sending the full set of items instead of trying to meticulously deduce what has actually changed which ends up semantically being a PATCH request.
Only rewrite to PATCH semantics if you have tangible facts indicating you need to optimize the API.