Home > database >  React: How to set up Edit Function in CRUD app to switch out whole components while keeping id
React: How to set up Edit Function in CRUD app to switch out whole components while keeping id

Time:03-18

Hey Guys I'm pretty new to React and I'm running into a bit of a pickle here. I'm making a simple CRUD website creator and I've got the add and delete function created and they work great! but I'm having trouble with the edit function.

I've based this on the this tutorial which works with String data-type https://www.digitalocean.com/community/tutorials/react-crud-context-hooks

So in my mind this is how it should should work

I've got use state as passing an object with a couple of properties

const [selectedSection, setSelectedSection] = useState({
id: null,
section: {},

});

I've set the id to the current component I'm editing with

const currentSectionId = route.match.params.id;

in my useEffect I'm carrying over the current id with while setting the new compenent skipping the id in the current section

  useEffect(() => {
const sectionId = currentSectionId;
const selectedSection = sections.find(
  (currentSectionTraversal) => currentSectionTraversal.id === parseInt(sectionId)
);
    setSelectedSection(selectedSection);},[currentSectionId, sections]);

  const onSubmit = (e) => {
    e.preventDefault();
    editSection(selectedSection);
    history.push("/");
    console.log("selectedSection id",selectedSection.section, selectedSection.id)
  };

and the button function to spread the selectedSection and change the only the requested value in the button.

const handleOnChange = (userKey, newValue) => setSelectedSection({ ...selectedSection, [userKey]: newValue });

in my render code I've got my button set up like

<button href="/" className="bg-green-400 w-mt hover:bg-green-500 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"                
                  value={selectedSection.section}
                  onChange={() => handleOnChange("section", QuickLinks)}
                  
                  type="submit"
                  >Add Section</button>

Now I've tried different things like changing the data-type in the useState Object, having the setSelectedSection in use effect to change the SelectedSection.section but in the console what I'm noticing is the button is not carrying the data over.

I've imported my compenent as Quicklinks but I'm not sure why it's not passing the component into the selectedSection.section

here is the entire code of the editSection

import React, { useState, useContext, useEffect} from "react";
import { useHistory, Link } from "react-router-dom";

import { GlobalContext } from "./GlobalState";

import QuickLinks from '../components/sections/quick_links/quickLinks';
import QuickLinksPreview from './images/quick-link.jpg';

export const EditSection = (route) => {
  let history = useHistory();

  const { sections, editSection } = useContext(GlobalContext);

  const [selectedSection, setSelectedSection] = useState({
    id: null,
    section: {},
  });

  const currentSectionId = route.match.params.id;

  useEffect(() => {
    const sectionId = currentSectionId;
    const selectedSection = sections.find(
      (currentSectionTraversal) => currentSectionTraversal.id === parseInt(sectionId)
    );
    setSelectedSection(selectedSection);
  }, [currentSectionId, sections]);

  const onSubmit = (e) => {
    e.preventDefault();
    editSection(selectedSection);
    history.push("/");
    console.log("selectedSection id",selectedSection.section, selectedSection.id)
  };

  const handleOnChange = (userKey, newValue) => setSelectedSection({ ...selectedSection, [userKey]: newValue });

  if (!selectedSection || !selectedSection.id) {
    return <div>Invalid Employee ID.</div>;
  }
    
    return (
        <React.Fragment>
          
          <div className="w-full container mt-20 mx-auto">
            <form onSubmit={onSubmit}>

              <table>
                <tbody>
                {/* ----------------------------Item List Start COPY------------------------ */}          
                  <tr>
                    <td className="px-6 py-4 whitespace-nowrap">

                      <div className="flex items-center">

                        <div className="flex-shrink-0 h-40 w-50 shadow">
                          <img className="h-40 w-full " src={QuickLinksPreview} alt="" />
                        </div>

                      </div>

                    </td>

                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm text-gray-900">Quick Links</div>
                      <div className="text-sm text-gray-500">Multi Card Quick Links<br></br>for Description and links</div>
                    </td>

                    <td className="px-6 py-4 whitespace-nowrap">
                        <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-white-800"> Beta </span>
                        {/* Component Development Status
                          <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-red-100 text-black-800"> Constrution </span>
                        <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800"> Active </span>
                        <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-yellow-100 text-black-800"> Testing </span>
                        */}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">S03-S5</td>
                      {/* Pricing Levels as Structure
                            S = Labels that it is sections
                            02 = is the Template Id for Developers
                            S = Standard Price
                            3 = Price level
                      */}
                    <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                    <button href="/" className="bg-green-400 w-mt hover:bg-green-500 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"                
                      value={selectedSection.section}
                      onChange={() => handleOnChange("section", QuickLinks)}
                      
                      type="submit"
                      >Add Section</button>
                      
                    </td>
                  </tr>
                  {console.log("Selected section", selectedSection.section)}
                  {/* ----------------------------Item List END COPY------------------------ */}       
                </tbody>
              </table>

              <div className="flex items-center justify-between">  
                <div className="block mt-5 bg-red-400 w-full hover:bg-red-500 text-white font-bold py-2 px-4 rounded focus:text-gray-600 focus:shadow-outline">
                  <Link to="/">Cancel</Link>
                </div>
              </div>

            </form>
          </div>
        </React.Fragment>
      );
};

CodePudding user response:

Try using onClick instead of onChange for the button. I think onChange is for <input> tags not buttons. Also href is for links, not buttons. Unless this button is in a form type=submit isn't necessary. Also an arrow function isn't required for onClick. onChange={() => handleOnChange("section", QuickLinks)} -> onClick={handleOnChange("section", QuickLinks)}.

  • Related