javascriptreactjspostaxiosfetch

How to post the time ReactJs


In the following code, I post objects.

Is it possible to post the time at which the post was made?

postbackend = () =>{
const config = {    
method: "POST",
headers: {
  "Content-Type": "application/json",
},
body: JSON.stringify({...this.state, items:this.props.items}),
};
const url = entrypoint + "/alluserpls"; 
fetch(url, config)
.then(res => res.json())
.then(res => {
  if (res.error) {
    alert(res.error);
  } else {
    alert(`ajouté avec l'ID ${res}!`);
  }
}).catch(e => {
  console.error(e);
}).finally(()=>this.setState({ redirect: true }));
}

I would simply like to recover the time at which the post was made


Solution

  • body: JSON.stringify({...this.state, created: new Date().toISOString(), items:this.props.items})
    

    This will add the timestamp to the POST body.

    You should take into consideration the fact this is considered to be a bad practice. Because users might have different time on their computers. That could lead to inconsistencies. The best way to solve the problem would be to set up the date/time on the server.