Trytobegood
Trytobegood

Reputation: 7

I have to refresh the page to see the change in REACTJS

I'm working on a simple project receving input and adding the input data to into database.

Here is my code:

 const [dataFromDB, setDataFromDB] = useState(null);

  const fetchDataFromDB = async () => {
    try {
      const response = await fetch(url);
      const data = await response.json();
      setDataFromDB(data);
      console.log(data);
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    fetchDataFromDB();
  }, []);

  const addTextToDB = async (text) => {
    try {
      await fetch('http://localhost:3001/api/codes', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          text: text,
        }),
      });
    } catch (error) {
      console.error(error);
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    const input = e.target.elements.name.value;
    addTextToDB(input);
    e.target.reset();
    fetchDataFromDB();
    setDataFromDB(dataFromDB);
    console.log(dataFromDB);
  };

  return (
    <div className="App">
      <form onSubmit={handleSubmit}>
        <label>
          Name:
          <input type="text" name="name" />
        </label>
        <input type="submit" value="ADD" />
      </form>
      <div>
        {dataFromDB &&
          dataFromDB.map((item) => <Item key={item._id} name={item.text} />)}
      </div>
    </div>
  );
}

First I fetch the data to show database to the user, then when a user input something by pressing the button the inputted value will be added to db. but to see the change I hvae to refresh the page or add two or more input after each other.

I have no idea where the problem is, after sumbitting the data I fetch the data again to receive the updated response from the database and then update the state of setDataFromDB to see the changes.

Upvotes: 0

Views: 44

Answers (1)

Invulner
Invulner

Reputation: 2053

In the handleSubmit function, you are calling the fetchDataFromDB function and then immediately setting the state of setDataFromDB to the current value of dataFromDB. This is unnecessary because you already update the state of dataFromDB inside the fetchDataFromDB function.

Moreover when you call addTextToDB and fetchDataFromDB in sequence like this, they will both start executing at the same time and run concurrently. Depending on the relative speeds of these functions and the server response times, it's possible that fetchDataFromDB may execute and update the state of dataFromDB before addTextToDB has completed adding the new data to the database. You should ensure that addTextToDB is fully completed and the database is updated before calling fetchDataFromDB to fetch the latest data from the server.

const handleSubmit = async (e) => {
  ...
  await addTextToDB(input);
  ...
  await fetchDataFromDB();
}

Upvotes: 0

Related Questions