{"id":26540300,"url":"https://github.com/saranatour1/react","last_synced_at":"2025-12-30T19:29:45.003Z","repository":{"id":172433342,"uuid":"649083247","full_name":"saranatour1/React","owner":"saranatour1","description":"A Part of the coding Dojo Program, All the submissions from  04.06.2023 - 25.06.2023 ","archived":false,"fork":false,"pushed_at":"2024-02-18T15:35:45.000Z","size":1721,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-02-19T00:23:29.537Z","etag":null,"topics":["dont-use-cra","mongodb","mongoose","nextjs","react-router","react-router-dom","reactjs","socket-io","vite"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/saranatour1.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2023-06-03T18:09:43.000Z","updated_at":"2024-02-19T00:23:29.538Z","dependencies_parsed_at":"2024-02-18T00:33:40.351Z","dependency_job_id":null,"html_url":"https://github.com/saranatour1/React","commit_stats":null,"previous_names":["saranatour1/react"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/saranatour1%2FReact","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/saranatour1%2FReact/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/saranatour1%2FReact/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/saranatour1%2FReact/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/saranatour1","download_url":"https://codeload.github.com/saranatour1/React/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244890102,"owners_count":20527030,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dont-use-cra","mongodb","mongoose","nextjs","react-router","react-router-dom","reactjs","socket-io","vite"],"created_at":"2025-03-22T00:30:13.418Z","updated_at":"2025-12-30T19:29:44.948Z","avatar_url":"https://github.com/saranatour1.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 🚨 Attention 🚨\n\u003e This repository is no longer maintained, Due to my focus on new projects and commitments! Please be cautious if you decide to use any information from this repository, as it may be outdated or no longer accurate.  \n### I was using create-react-app here, here's why its no longer used \nA good article on this: [Link](https://dev.to/ag2byte/create-react-app-is-officially-dead-h7o#:~:text=The%20problem%20with%20CRA)   \ncheck this to see which frameworks support React ==\u003e [Link](https://react.dev/learn/start-a-new-react-project#production-grade-react-frameworks)   \nA good runner up after [Vite](https://vitejs.dev/guide/) is nextJS in my opinion =\u003e [Link](https://github.com/vercel/next.js)  \n\n# Steps to edit the functionality\n\na personal recommendation is to create a template folder containing server and client folders.\n\n## Backend General Functionality\n\nMake sure that you have the server off , create 4 folders, config , controllers , routes, models , and a server.js. This is for Modularization and Organization purposes.\n\n### Config Folder\n\nThis folder is where you host the connection to the db, since I am using Mongoose and Mongo db, the File structure would look like this, after you create a file called ‘mongoose.config.js’: \n\n```jsx\nconst mongoose = require(\"mongoose\");\n\nmongoose\n  .connect(\"mongodb://127.0.0.1:27017/authors\", {\n    // if there is no db, it will create a new one\n    useNewUrlParser: true,\n    useUnifiedTopology: true,\n  })\n  .then(() =\u003e console.log(\"Established a connection to the database\"))\n  .catch((err) =\u003e\n    console.log(\"Something went wrong when connecting to the database \", err)\n  );\n```\n\n### Models Folder.\n\nin the Models folder, create a file for every Table you might have, and name it in the name of the table/document. ‘for instance ‘authors.models.js’’  ,  it should look something like this: \n\n```jsx\nconst mongoose = require(\"mongoose\");\n\nconst authorsSchema = new mongoose.Schema(\n  {\n    name: {\n      type: String,\n      required: [true, \"title is required\"],\n      minLength: [2, \"title needs to be at least 10 charecter\"],\n    },\n  },\n  {\n    timestamps: true,\n  }\n);\n\nconst Author = mongoose.model(\"author\", authorsSchema);\n\nmodule.exports = Author;\n\n```\n\nif you have multiple documents, each  table could have a file for it as will as a module.export . \n\n### Controllers\n\nin the controllers folder, make a file called `authors.controller.js` and each table will have a controller file, and this is what it looks like: \n\nfirst , import the model \n\n```jsx\nconst Author = require(\"../models/authors.model\");\n```\n\n- The See all function\n    \n    ```jsx\n    module.exports.findAllAthors = (req, res) =\u003e {\n      // console.log(\"all \");\n      Author.find()\n        .then((allAthors) =\u003e {\n          res.json(allAthors); // this line is edited\n        })\n        .catch((err) =\u003e {\n          res.json({\n            message: \"Something went wrong in retrieving all the Athors \",\n            error: err,\n          });\n        });\n    };\n    ```\n    \n- find a single object:\n    \n    ```jsx\n    module.exports.findOneSingleAuthor = (req, res) =\u003e {\n      console.log(\"hi\");\n      Author.findOne({ _id: req.params.id })\n        .then((Author) =\u003e {\n          res.json(Author); // this line is edited\n        })\n        .catch((err) =\u003e {\n          res.json({\n            message: \"Something went wrong in retrieving a single Author \",\n            error: err,\n          });\n        });\n    };\n    ```\n    \n- create a new object:\n    \n    ```jsx\n    // Refactored creating an object function, to create an array instead of an object\n    module.exports.createNewAuthor = (req, res) =\u003e {\n      // console.log(req);\n      const { name } = req.body;\n      Author.create({\n        name\n      })\n        .then((lastCreatedAuthor) =\u003e {\n          res.json(lastCreatedAuthor);\n          // console.log(lastCreatedAuthor);\n        })\n        .catch((err) =\u003e {\n          res.json({\n            message: \"Something went wrong with creating a new Author \",\n            error: err,\n          });\n        });\n    };\n    ```\n    \n- update an object:\n    \n    ```jsx\n    // updated this function so that it updated the vaalues , but does not return an object.\n    module.exports.updateAuthor = (request, response) =\u003e {\n      // console.log(request.body);\n      Author.findOneAndUpdate({ _id: request.params.id }, request.body, {\n        new: true,\n      }) // this line is edited\n        .then((updatedAuthor) =\u003e {\n          response.json(updatedAuthor);\n          console.log(updatedAuthor);\n        })\n        .catch((err) =\u003e {\n          res.json({\n            message: \"Something went wrong with Updating a Author \",\n            error: err,\n          });\n        });\n    };\n    ```\n    \n- Delete an object:\n    \n    ```jsx\n    // delete a product by id\n    module.exports.deleteAuthor = (request, response) =\u003e {\n      // console.log(request.body);\n      Author.deleteOne({ _id: request.params.id })\n        .then((deleteConfirmation) =\u003e response.json(deleteConfirmation))\n        .catch((err) =\u003e response.json(err));\n    };\n    ```\n    \n\n### Routes Folder\n\nThe place where you define your routes , and define what is happening when we visit them, name the file as ‘something.routes.js’, do a : \n\n```jsx\nconst AuthorsController = require('../controllers/authors.controller');\n \nmodule.exports = app =\u003e {\n    app.get('/api/authors', AuthorsController.findAllAuthors);\n    app.get('/api/authors/:id', AuthorsController.findOneSingleAuthor);\n    app.put('/api/authors/:id/edit', AuthorsController.updateAuthor);\n    app.delete('/api/authors/:id', AuthorsController.deleteAuthor);\n    app.post('/api/authors', AuthorsController.createNewAuthor);\n}\n```\n\nand now last but not least, server.js \n\n### Server.js\n\nthis is the place that holds up all the functionality:- \n\n```jsx\nconst mongoose = require('mongoose');\nconst express = require(\"express\");\nconst app = express();\nconst allAuthorsRoutes = require(\"./routes/authors.routes\");\nconst cors = require('cors');\nconst port = 8000; \napp.use(cors());\n\nrequire(\"./config/mongoose.config\");\n\napp.get(\"/api\", (req, res) =\u003e {\n  res.json({ message: \"Hello World\" });\n});\n\napp.use(express.json(), express.urlencoded({ extended: true }));\n    \n\nallAuthorsRoutes(app);\n    \napp.listen(port, () =\u003e console.log(`The server is all fired up on port ${port}`));\n```\n\nand There we go!, We are all set up in the backend ,lets check out postman. \n\n## Front End functionality\n\ninstall react-router-dom, axios , and any other thing you might need. then start working\n\nin the case of this assignment: authors, this the steps I took. \n![Untitled](https://github.com/saranatour1/React/assets/77834808/82c40704-007d-4440-a006-b376666d689c)\n\n\n\n### Main root\n\nWe have a heading that’s shared across , so we can make it into a component, as well as the button to indicate the location. \n\n**************Header.js************** \n\n```jsx\nimport React, { useState } from 'react';\nimport { Link, useLocation } from 'react-router-dom';\n\nfunction Header() {\n  const [linkPath, setLinkPath] = useState({ '/new': 'Add a new author' });\n  const location = useLocation();\n\n  console.log(location.pathname);\n\n  // Update the linkPath based on the location.pathname\n  useState(() =\u003e {\n    if (location.pathname === '/') {\n      setLinkPath({ '/new': 'Add a new author' });\n      console.log(\"am i here\");\n    } else {\n      setLinkPath({ '/': 'Home' });\n    }\n  }, []);\n  const linkKey = Object.keys(linkPath)[0];\n  const linkValue = Object.values(linkPath)[0];\n\n  // console.log(linkKey,linkValue,linkPath)\n  return (\n    \u003cdiv\u003e\n      \u003ch3\u003eFavorite Authors\u003c/h3\u003e\n      \u003cLink to={linkKey}\u003e{linkValue}\u003c/Link\u003e\n    \u003c/div\u003e\n  );\n}\n\nexport default Header;\n```\n\nNow to do iterate over the authors and show delete and edit buttons, this goes as follows: \n\nthe Display Component : \n\n```jsx\nimport React, { useState, useEffect } from 'react';\nimport axios from 'axios';\nimport { Link } from 'react-router-dom';\nimport DeleteButton from './DeleteButton';\n\nfunction Display({ removeFromDom, items }) {\n  const [authors , setAuthors] = useState(items);\n  // const [loaded, setLoaded] = useState(false);\n\n  // get all the products \n\n// http://localhost:8000/api/authors/\n  return (\n\n    \u003ctable\u003e\n      \u003cthead\u003e\n        \u003ctr\u003e\n          \u003cth\u003eName\u003c/th\u003e\n          \u003cth\u003eEdit\u003c/th\u003e\n          \u003cth\u003eDelete\u003c/th\u003e\n        \u003c/tr\u003e\n      \u003c/thead\u003e\n      \u003ctbody\u003e\n        {items.map((item, idx) =\u003e (\n          \u003ctr key={idx}\u003e\n            \u003ctd\u003e\n              \u003cLink to={`/authors/${item._id}`}\u003e{item.name}\u003c/Link\u003e\n            \u003c/td\u003e\n            \u003ctd\u003e\n              \u003cLink to={`/authors/${item._id}/edit`}\u003eEdit\u003c/Link\u003e\n            \u003c/td\u003e\n            \u003ctd\u003e\n              \u003cDeleteButton removeFromDom={removeFromDom} id={item._id} /\u003e\n            \u003c/td\u003e\n          \u003c/tr\u003e\n        ))}\n      \u003c/tbody\u003e\n    \u003c/table\u003e\n\n  \n  );\n}\n\nexport default Display;\n```\n\nand the Main page now looks like this: \n\n```jsx\nimport React, { useEffect, useState } from 'react'\nimport FormInput from '../components/FormInput';\nimport Display from '../components/Display';\nimport axios from 'axios';\nimport Header from '../components/Header';\n\nfunction MainPage() {\n  // lets do all the editing here? \n  \n  // grab all the things that were on formInput, and transfer them here\n\n  // const [price, setPrice] = useState(0);\n  // const [descreption, setDescreption] = useState(\"\");\n  // const [products, setProducts] = useState([]); // must change the above to be a Single object rather than attributes \n  const [loaded, setLoaded] = useState(false);\n  const [authors , setAuthors] = useState([]);\n\n    // get all the previous items that were there \n\n    useEffect(() =\u003e {\n      const fetchData = async () =\u003e {\n        try {\n          const response = await axios.get('http://localhost:8000/api/authors');\n          // setProducts(response.data);\n          setAuthors(response.data);\n          setLoaded(true);\n        } catch (err) {\n          console.log(err);\n        }\n      };\n      fetchData();\n    }, []);\n    \n    // Take out the remove from Dom in 'Display' Component\n    const removeFromDom = authorId =\u003e {\n      setAuthors(authors.filter(author =\u003e author._id !== authorId));\n  }\n\n  return (\n    \u003cdiv\u003e\n      \u003cHeader /\u003e\n      {loaded \u0026\u0026 \u003cDisplay removeFromDom={removeFromDom}\n       items={authors} \n       /\u003e}\n    \u003c/div\u003e\n  )\n}\n\nexport default MainPage;\n```\n\n### Add a New Item page\n\nThe page Structure is now Going to be like this: \n\n```jsx\nimport React, { useState } from 'react'\nimport FormInput from '../components/FormInput';\nimport axios from 'axios';\nimport Header from '../components/Header';\n\nfunction AddAuthorPage() {\n  const [name, setName] = useState(\"\");\n  const [authors, setAuthors] = useState([]);\n  const [errors, setErrors] = useState([]);\n\n  const createAuthor = person =\u003e {\n    axios.post('http://localhost:8000/api/authors/', person)\n      .then(res =\u003e {\n        setAuthors([...authors, res.data]);\n        setErrors([]);\n      })\n      .catch(err =\u003e {\n        if (err.response \u0026\u0026 err.response.data \u0026\u0026 err.response.data.errors \u0026\u0026 err.response.data.errors.name) {\n          const errorResponse = err.response.data.errors.name;\n          const errorArr = Object.values(errorResponse).map(error =\u003e error.message);\n          setErrors(errorArr);\n        } else {\n          setErrors([\"An error occurred while creating the author.\"]);\n        }\n      });\n  };\n\n  return (\n    \u003cdiv\u003e\n      \u003cHeader /\u003e\n      \u003cFormInput\n        onSubmitProp={createAuthor}\n        initialName=\"\"\n        errMsg={errors}\n      /\u003e\n    \u003c/div\u003e\n  );\n}\n\nexport default AddAuthorPage;\n```\n\nwhere we already made The Header , and the formInput. So we are done :D:D:D: \n\n### update Page\n\nI prefer to keep both pages separated even though they are exactly the same. \n\n```jsx\nimport axios from 'axios';\nimport React, { useEffect, useState } from 'react'\nimport { useNavigate, useParams } from 'react-router-dom';\nimport Header from '../components/Header';\nimport FormInput from '../components/FormInput';\n\nfunction UpdateAuthor() {\n  const { id } = useParams();\n  const [author, setAuthor] = useState({});\n  const [loaded, setLoaded] = useState(false);\n  const [errors , setErrors] = useState();\n\n  const navigate = useNavigate();\n  //get request \n  useEffect(() =\u003e {\n    axios\n      .get(`http://localhost:8000/api/authors/${id}`)\n      .then(res =\u003e {\n        console.log(res.data);\n        setAuthor(res.data);\n        setLoaded(true);\n      })\n      .catch(err =\u003e console.log(err));\n  }, []);\n\n// update  \nconst updateAuthor = author =\u003e {\n  // e.preventDefault();\n  console.log('Trying to update');\n  axios\n    .put(`http://localhost:8000/api/authors/${id}/edit`, author)\n    .then(res =\u003e {console.log(res); navigate('/');})\n    .catch(err =\u003e {\n      if (err.response \u0026\u0026 err.response.data \u0026\u0026 err.response.data.errors \u0026\u0026 err.response.data.errors.name) {\n        const errorResponse = err.response.data.errors.name;\n        const errorArr = Object.values(errorResponse).map(error =\u003e error.message);\n        setErrors(errorArr);\n      } else {\n        setErrors([\"An error occurred while editing the author.\"]);\n      }\n    });\n};\n\nif (!loaded) {\n  return \u003cp\u003eLoading...\u003c/p\u003e;\n}\n\n  return (\n    \u003cdiv\u003e\n      \u003cHeader /\u003e \n      \u003ch3\u003eUpdate this author  \u003c/h3\u003e\n      \u003cFormInput\n        onSubmitProp={updateAuthor}\n        initialName={author.name}\n        errMsg={errors}\n      /\u003e\n    \u003c/div\u003e\n  )\n}\n\nexport default UpdateAuthor;\n```\n\nbut the validations don’t work :D:D:D:D:DD:D:\n\nI guess that’s it.\n\nCheck out these for minor help: \n\n[React Docs](http://React.dev)\n\n[React Router docs](https://reactrouter.com/en/main/components/link) \n\n[MDN - JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript) \n\n[axios documintation](https://axios-http.com/docs/intro) \n\n[Mongoose Documentation](https://mongoosejs.com/docs/index.html) \n\n[Mongodb Manual](https://www.mongodb.com/docs/manual/) \n\nDocumenting the documentation ? Sounds like a pretty good idea.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsaranatour1%2Freact","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsaranatour1%2Freact","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsaranatour1%2Freact/lists"}