I am wanting to make my website able to add a name and dog breed to an existing list of animals.
export const addNewPlayer = async (playerObj) => {
try {
const response = await fetch(
`${APIURL}players/`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: 'Rufus',
breed: 'Irish Setter',
}),
}
);
const result = await response.json();
console.log(result);
} catch (err) {
console.error(err);
}
};
This is the function to create the new player
let form = document.querySelector('#new-player-form > form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
let playerData = {
name: form.elements.name.value,
breed: form.elements.breed.value
}
console.log(playerData)
const players = await fetchAllPlayers()
renderAllPlayers(players)
addNewPlayer(playerData);
renderNewPlayerForm()
});
This is the form that I have here too.
I am just stumped on how to change the "Rufus" and "Irish Setter" to user inputs. When logging the playerData, I can see it running when inspecting, but it only adds the spot for "Rufus".
Some of the code was given, and I am only stumped on the playerObj parameter that was first in the code. I do not see a use, and most of the stuff in addNewPlayer is also given in the API website that was a part of the project. I tried to make the name and breed empty strings but got an error from that.
CodePudding user response:
All the information you need is in your playerData
variable. So, just add the info from it inside your requisiton body. try this:
export const addNewPlayer = async (playerObj) => {
//...
body: JSON.stringify({
name: playerObj.name,
breed: playerObj.breed,
}),