I am trying to make an update functionality works. If a person name already exist and I filled in the phone number, it will say smthg like,
name already exist, replace the phone number instead?
If the person name does not exist, it will create a new object and store the info in the database. The problem right now is that I keep on getting errors ‘PUT http://localhost:3001/persons/undefined 404 (Not Found)’ . I see that the undefined is related to id
. But I already included it in the parameter of the function as well as in update
method. How can I fix this ? Here is the code,
const App = () => {
const [persons, setPersons] = useState([])
const [newName, setNewName] = useState('')
const [newNumber, setNewNumber] = useState('')
const [searchTerm, setSearchTerm] = useState("")
const addName = (event, id) => {
event.preventDefault()
const nameObject = {
name: newName,
number: newNumber
}
const isNameExist = (value) => persons.some(person => person.name.includes(value))
const changeNumberText = 'is already added to phonebook, replace the old number with a new one ?'
if ( isNameExist(nameObject.name) && window.confirm(`${isNameExist(nameObject.name)} ${changeNumberText}`)) {
personService
.update(id, nameObject)
.then(response => {
setPersons(persons.concat(response.data))
setNewName('')
setNewNumber('')
})
} else if(!isNameExist(nameObject.name)) {
personService
.create(nameObject)
.then(response => {
setPersons(persons.concat(response.data))
setNewName('')
setNewNumber('')
})
}
}
................
persons.js
import axios from 'axios'
const baseUrl = 'http://localhost:3001/persons'
const getAll = () => {
return axios.get(baseUrl)
}
const create = newObject => {
return axios.post(baseUrl, newObject)
}
const update = (id, newObject) => {
return axios.put(`${baseUrl}/${id}`, newObject)
}
const deletePerson = (id) => {
return axios.delete(`${baseUrl}/${id}`)
}
export default {
getAll: getAll,
create: create,
update: update,
delete: deletePerson
}