JohnPix
JohnPix

Reputation: 1843

Where to store changeable data?

I'm using NextJs. I have 10 buttons, and 0 score. If I click one button the score should be increased only by one point, no matter how many times I click, and the maximum score can be 10. At the same time I can not disable buttons. The question is which way is the best to implement such task?

In my mind there are two ways, but I don't think that they are right:

First, I have db and store there 10 button ids with 0 or 1 points, and I validate my response if it returns 0 or 1. For example: [{btn_1:0}, {btn_2:1},..., {btn_7:0}, ...]. The problem is here, it will be a lot of requests to db.

The second way, is to keep button ids and score in local storage and somehow within some period of time synchronize it with db. (I haven't worked with local storage, but I believe it's possible🙂)

Upvotes: 0

Views: 87

Answers (3)

Willey Ohana
Willey Ohana

Reputation: 402

The second solution is going to be much faster for the user. API calls can take a while to resolve depending on internet speeds.

I would store data in local storage, then use a useEffect to create an Interval that can periodically update your database from the local storage values:

  // Set up interval to put data into DB
  useEffect(() => {
    // Choose how frequently this update will run
    const secondsBetweenUpdates = 10;

    const intervalId = setInterval(() => {
      const score = localStorage.getItem('score');

      // A lazy API call. Call whatever your url is and pass it the data
      axios.put('/api/score', { score: score })
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        })
    }, secondsBetweenUpdates * 1000);

    // Always clean up intervals created in useEffect
    return () => clearInterval(intervalId);
  }, []);

You would want another useEffect to fetch the data from the DB to give to the user when the app loads in:

  // Fetch data from DB and update localStorage
  useEffect(() => {
    axios.get('/api/score')
      .then((res) => {
        const savedScore = res.data;
        localStorage.setItem('score', JSON.stringify(savedScore));
      })
      .catch((err) => {
        console.log(err);
      })
  }, []);

Upvotes: 1

Gustavo Máximo
Gustavo Máximo

Reputation: 6200

If your concern is to communicate dynamic data between components, you should look into state management tools such as React's Context or Redux (I highly recommend RTK). This data will only be available while the application is running, mind you. If you wish to make it available whenever the user closes the app and returns, you could use localStorage. But I would advise against using it as anything more than just a temporary data storage tool. You should still aim to utilize a database as the main source of truth.

Upvotes: 1

Arsalan-Zahid
Arsalan-Zahid

Reputation: 1

Look into the useState hook:

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

From https://reactjs.org/docs/hooks-state.html

Upvotes: 0

Related Questions