Fetching and submitting forms to server in react
Published: 2022-09-22 20:29:47

Thinking about how far I have gotten in my coding journey and now looking back I see that I have improved a lot since I started. Now I'm on my second project and I feel great about it. Out of all the problems I ran into while creating my project one of them stood out the most. The problem that stood out the most was submitting a form to the server. I want to explain my process of completing this task and how it felt to put everything together to finally complete a project.

First off let's talk about what my project is. My project is called the Jokes app it gives out random jokes. It gives you the answer to the joke and lets you create your joke on the creates jokes. The new joke you create also gets added to the list of random jokes. Doesn't this sound awesome? 

Alright, to get started I made a db.json file to hold all the information about the random jokes. This is how it looks:
{
  "Jokes": [
    {
      "id": 1,
      "joke": "Why did the scarecrow win an award? ",
      "answer": "Because he was outstanding in his field."
    },
    {
      "id": 2,
      "joke": "Why did the melon jump into the lake? ",
      "answer": "It wanted to be a water-melon."
    },
    {
      "id": 3,
      "joke": "What do you call a pig that does karate? ",
      "answer": "A pork chop."
    },
    {
      "id": 4,
      "joke": "How does the ocean say hello? ",
      "answer": "It waves."
    },
    {
      "id": 5,
      "joke": "Where do you learn to make banana splits? ",
      "answer": "At sundae school."
    },

These are all the preset jokes that will be in my random jokes array.

Side note: You must have an id number attached to the data for your server to run correctly.

I later installed JSON Server using this command "npm install -g json-server".
Then I started the JSON Server with the command "json-server --watch db.json".

Now my server is up and running. Any POST, PUT, PATCH or DELETE requests, or changes will be automatically and safely saved to db.json.

Now I started working on my fetching request. I used this fetch request to retrieve the information from my db.json which are my jokes like this:

useEffect(()=>{
        fetch("http://localhost:3000/Jokes")
            .then(resp => resp.json())
            .then(data => setJokes(data))            
            .catch(console.error())
    },[]
    )

To set them in my setJoke variable array.
So now that I have my joke saved in that variable, I can manipulate them how I want. I made them later pop up on the screen any time my get random jokes button was pressed in random order.

Now for handling the submit:

function handleSubmit(e){
       e.preventDefault()
       const newJoke = {
           ...formData
       }
      
       
        console.log(formData)
        fetch('http://localhost:3000/Jokes', {
        method: 'POST',
        headers: { 'Content-type': 'application/json', },
        body: JSON.stringify(newJoke),
        })
        .then((resp) => 
           {
          console.log(resp)
          console.log(newJoke)
          return resp.json()}
        )
        .then(onAddJoke)
        .catch((error)=>console.log(error))

I created the handleSubmit function to save the text that was in the formdata in the newJoke variable. Then I created a POST request for the submit button. When the submit button gets pressed the data gets updated on the db.json with the new joke.

This is how I was able to correctly handle submits and fetch data in my project. Now looking back at everything it was fairly easy to create.