DEV Community

Mare
Mare

Posted on

Changing a state and updating the changes with a put request

Hi !

I'm trying to change the state of an element in the React component, while in the same time updating the data with a put request.

There's an element "Pending" in the React component, and i'm looking to change it to "Paid".

Here's the code:

const [invoice, setInvoice] = useState([])

const paidInvoice =  () => {
    setInvoice((invoice) => {
      return({
        ...invoice,
        status:'Paid'
      });
    })

axios.put('http://localhost:5000/api/invoice/update/'+id, invoice)
    .then(response => console.log(response.data))
    .catch(error => console.log(error))
}

Enter fullscreen mode Exit fullscreen mode

The problem is that when i call this function after a click, the state changes, but the data is not updated so when i refresh the page it's still the same as before clicking.

The invoice object that i get:
Image description
(The status must be paid not pending)
I also noticed that when i click two consecutive times to call the function, the problem resolves and the data updates correctly in the database...

Top comments (1)

Collapse
 
mare profile image
Mare

I tried to change the format to this but it didn't get solved.

 function editStatus(){
    setInvoice((invoice) => {
      return({
        ...invoice,
        status:'Paid'
      });
    })
  }

  function updateStatus() {
    axios.put('http://localhost:5000/api/invoice/update/'+id, invoice)
    .then(response => console.log(response.data))
    .catch(error => console.log(error))
  }

  const paidInvoice =  () => {   
    editStatus();
    updateStatus();
  }
Enter fullscreen mode Exit fullscreen mode

The only way for me to update the data is to click to call the function two consecutive times.