-4

Here is my code, I add a new text to the database and it works perfectly I can see it in my database, but when I want to update the display, despite I retrieve the new data from the database and update the state of the data with the latest data, it still shows the old data when I log it.

 const submit = async (e) => {
    e.preventDefault();
    const code = e.target.elements['text'].value;

      try {
        addTextToDataBase(text);
        console.log('text added to database');
        const response = await fetch(url);
        const data = await response.json();
        setDataFromDB(data);
        console.log(data);
      } catch (e) {
        console.log(e);
      }
  };

Here is the addCodeToDB function:

const addCodeToDB = async (code, percentage) => {
    try {
      await fetch('http://localhost:3001/api/codes', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          code: code,
          percentage: percentage,
          status: 'active',
        }),
      });
    } catch (error) {
      console.error(error);
    }
  };
Xab Ion
  • 1,105
  • 1
  • 11
  • 20
  • how is the `submit` function called ? also the console.log(data) does it display the correct result from the API ? – TGod-Ajayi Feb 26 '23 at 14:10
  • @TGod-Ajayi: its a button in a form, when you click on the submit button it passes the inputted text to the addTextToDatabase function and it sucessfully adds the text to the db. and yes the console.log display the correct result from the API but the old one (before adding a new text to db) and when you refresht the page the new text displays both in the page and in console log. – Suchagreat Feb 26 '23 at 14:15
  • 1
    Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – derFrosty Feb 26 '23 at 14:19
  • I'm guessing `addTextToDataBase` is an asynchronous operation. You're not waiting for the new data to be added before retrieving it. – Guy Incognito Feb 26 '23 at 14:20
  • @GuyIncognito yes exactly addTextToDataBase is an asynchronous. What change should I do to this code then to solve the problem? – Suchagreat Feb 26 '23 at 14:24
  • 1
    @Suchagreat do `await addTextToDatabase` and make sure the function itself is async – TGod-Ajayi Feb 26 '23 at 14:25
  • @TGod-Ajayi I added await before addTextToDatabase now the console log does not appear in the console at all! actually when I click the button nothing happens! – Suchagreat Feb 26 '23 at 14:27

2 Answers2

0

React doesn't update the state variable immediately after running the set function, rather it does comparison between current state variable and next state provided by new value, using Object.is. If both are different, react will go ahead and re-render and then state variable will be updated to new value. If you want to log value, you will need to use useEffect hook.

Example https://codesandbox.io/s/usestate-updating-state-forked-muimxt

Rishi
  • 1
  • 2
-1

React updates the state asynchronously, so your console.log is printing stale data. If you use something like React Dev Tools, you'll see that it's likely being updated correctly.