Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass on form inputs and add them to an array of objects?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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,
    }),
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading