Reputation: 199
I have a function which takes two inputs and makes a post request in react:
addNote(title, content){
this.setState({title: title, content: content, error: ''}, () => {
const newNote = {
title: this.state.title,
content: this.state.content,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString()
};
fetch('http://localhost:8000/notes', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(newNote)
})
.catch(error => {
this.setState({error: 'Error adding note.'});
console.error('Error during adding note', error);
})
const storedNotes = this.state.notes;
storedNotes.unshift(newNote);
this.setState({notes: storedNotes});
//Adding this.fetchNotes(); here does not work
});
}
fetchNotes(){
fetch('http://localhost:8000/notes')
.then(response => response.json())
.then(data => this.setState({isLoading: false, notes: data}))
}
The id of the note is something like 5b0fac246637e1005ca0a7b5 (given by mongoose). How can I get the id of a newly added item in react so that I can do other operations like updating and deleting notes in the route /notes/:noteId? When I add a note and try to delete it, there is a 404 error since the id is undefined. On page reload, the operations work fine. I don't want to make a post request in the server since the view is rendered by react.
I tried a get request of all the notes again after adding the note. It does not work as intended. The added note does not show immediately on submit.
Should I make a post request with an id myself, say, new Date().toISOString()?
Upvotes: 0
Views: 2335
Reputation: 938
Why don you return the new mongoose id after your POST request?
something like this:
addNote(title, content){
this.setState({title: title, content: content, error: ''}, () => {
const newNote = {
title: this.state.title,
content: this.state.content,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString()
};
fetch('http://localhost:8000/notes', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(newNote)
})
.then(response => response.json())
.then(data => {
// here data.id might contain your objectId
const storedNotes = this.state.notes;
storedNotes.unshift(newNote);
this.setState({notes: storedNotes});
//Adding this.fetchNotes(); here does not work
})
.catch(error => {
this.setState({error: 'Error adding note.'});
console.error('Error during adding note', error);
});
});
}
fetchNotes(){
fetch('http://localhost:8000/notes')
.then(response => response.json())
.then(data => this.setState({isLoading: false, notes: data}))
}
but this requires some refactoring of the your /notes endpoint on your server.
Upvotes: 1