skip to Main Content

I am creating a React + Express app that allows the user to make a list of webprojects that they would like to do. They are displayed in a table on the webpage and there is a form beneath the table which allows the user to make a new entry to the webprojects and an alert pops up to say a new entry has been added. I have been able to make the form and the table, however everytime I press the add button the alert does come up so I know my function works but it keeps on adding an empty object instead of the information the user entered in the form

server.js
const express = require('express');
const app = express();
const PORT = process.env.PORT || 5000;
const bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

let webProjects = [

  {
    ID: 1,
    TITLE: "React Game",
    DESCRIPTION: "Tic tac toe game created using Create React App",
    URL: "http://someURL/myapp/game/",
  },
  {
    ID: 2,
    TITLE: "Online Store",
    DESCRIPTION: "Online store created with HTML, CSS and Javascript.",
    URL: "http://someURL2/shop/index",
  },
  {
    ID: 3,
    TITLE: "Online Store",
    DESCRIPTION: "Online store created with HTML, CSS and Angular.",
    URL: "http://someURL3/shop2/index",
  }
] 

app.get("/api", (req, res) => {

    res.json({ webProjects });
})



app.post("/api/create", (req, res) => {

  response ={
    ID:req.body.id,
    TITLE:req.body.title,
    DESCRIPTION:req.body.description,
    URL:req.body.url,
  };


  res.json(response);
  webProjects.push(response);



})

app.listen(PORT, () => {
   console.log("Server started on port 5000")
})

FormData.js
import React, { useState } from 'react'

function FormData() {
    const [content, setContent] = useState({ webProjects: []})
    const [ID, setID] = useState("");
    const [TITLE, setTITLE] = useState("");
    const [DESCRIPTION, setDESCRIPTION] = useState("");
    const [URL, setURL] = useState("");

    const create = (e) => {
        fetch("/api/create", {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                TITLE,
                DESCRIPTION,
                URL,
            }),
        })
        .then((response) => response.json())
        .then((response) => {
            alert("A new item has been added")
            setContent(response.copyContent)
        })
    }
  return (
    <div>
        <form>
            <label>
                ID:
                <input
                    name="id"
                id="id"
                type="text"
                value={ID}
                onChange={(e) => setID(e.target.value)}
                required
                />
            </label>
            <label>
                Title:
                <input
                    name="title"
                    id="title"
                    type="text"
                    value={TITLE}
                    onChange={(e) => setTITLE(e.target.value)}
                    required
                />
            </label>
            <label>
                Description:
                <input
                    name="description"
                    id="description"
                    type="text"
                    value={DESCRIPTION}
                    onChange={(e) => setDESCRIPTION(e.target.value)}
                    required
                />
            </label>
            <label>
                URL:
                <input
                    name="url"
                    id="url"
                    type="text"
                    value={URL}
                    onChange={(e) => setURL(e.target.value)}
                    required
                />
            </label>
            <button className='add-btn' type="button" onClick={(e) => create(e)}>Add</button>
        </form>
    </div>
  )
}

export default FormData

App.js

import React, { useEffect, useState } from 'react'
import { TableData } from './components/TableData'
import FormData from './components/FormData'



function App() {

  const [content, setContent] = useState({ webProjects: []})

  useEffect(() => {
    fetch("/api", {
      method: "GET",
      headers: {
        "Content-type": "application/json",
      }
    }).then((response) => response.json()
    ).then((response) => {setContent(response)}
    )
  }, [])

  return (
    <div>
      <TableData projectData={content.webProjects}/>
      <FormData />
    </div>
  )
}

export default App

2

Answers


  1. It looks like you are not handling the state updates correctly in your FormData component. You are updating the content state in your create function without updating the webProjects array within it.

    .then((response) => {
        alert("A new item has been added")
        setContent((prevContent) => ({
            webProjects: [...prevContent.webProjects, response]
        })
        // And perhaps you want to reset some other states too?
        setID("")
        setTITLE("")
        setDESCRIPTION("")
        setURL("")
    )
    
    Login or Signup to reply.
  2. It appears the problem lies in the way you are handling the req.body keys.

    Based on the JSON you’re sending:

    {
      "TITLE": "test",
      "DESCRIPTION": "test",
      "URL": "http://test.com"
    }
    

    And considering your backend endpoint (app.post("/api/create")), here’s the corrected code for handling the request:

    response = {
        ID: req.body.id, // Assuming the ID is included in the request
        TITLE: req.body.TITLE, // Corrected key: `TITLE`, not `title`
        DESCRIPTION: req.body.DESCRIPTION, // Corrected key: `DESCRIPTION`, not `description`
        URL: req.body.URL, // Corrected key: `URL`, not `url`
    };
    

    Make sure to use the correct key names in your backend code to properly extract the values from the req.body object. Also, ensure that the keys in the JSON request match the case of the keys you’re trying to access in the backend.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search