Advertisement
EntropyStarRover

UpdateRecord

Dec 6th, 2021
654
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import styles from "./UpdateRecord.module.css";
  2. import { useState, useEffect } from 'react';
  3. import { useParams } from 'react-router-dom';
  4. import { useContext } from "react/cjs/react.development";
  5. import {AuthContext} from "../../Contexts/AuthContext";
  6. import * as beerService from "../../services/beer";
  7.  
  8. import recordFormValidation  from "../../utils/recordFormVlidation";
  9.  
  10. import Error from "../Error/Error";
  11. import { useNavigate } from 'react-router-dom';
  12.  
  13. function UpdateRecord() {
  14.  
  15.   const {user} =useContext(AuthContext);
  16.   const [beer, setBeer] = useState({});
  17.   const { beerId } = useParams();
  18.   const [rating, setRating] = useState(1);
  19.   const [hover, setHover] = useState(0);
  20.   const [errors, setErrors]=useState([]);
  21.   const navigate = useNavigate();
  22.  
  23.   function getRating(arr){
  24.     const valuesArr=arr.map(x=>x.value);
  25.     const sum = valuesArr.reduce(function(a, b){
  26.         return a + b;
  27.         }, 0);
  28.     const average= Math.round(sum/arr.length);
  29.     return average;        
  30.   }
  31.  
  32.   function checkIfUserIsOwner(ownerId){
  33.     if (!user._id===ownerId){
  34.      return navigate('/')
  35.     }
  36.   }  
  37.  
  38.   useEffect(() => {
  39.    async function fetchData(){
  40.     let beerResult = await beerService.getOne(beerId);
  41.     checkIfUserIsOwner(beerResult.ownerId);
  42.     setBeer(beerResult);
  43.     setRating(getRating(beerResult.rating))
  44.       }
  45.       fetchData()
  46. }, [beerId]);
  47.  
  48.  
  49. const onBeerUpdate = (e) => {
  50.   e.preventDefault();
  51.   let formData = new FormData(e.currentTarget);
  52.  
  53.   let title = formData.get('beerName');  
  54.   let imgUrl = formData.get('beerPicture');
  55.   let type = formData.get('beerTypes');
  56.   let country=formData.get('beerOrigin');
  57.   let alcVol=formData.get('alcoholicContent');
  58.  
  59.   const updatedBeer=Object.assign(beer);
  60.   updatedBeer.title=title;
  61.   updatedBeer.imgUrl=imgUrl;
  62.   updatedBeer.type=type;
  63.   updatedBeer.country=country;
  64.   updatedBeer.alcVol=alcVol;
  65.  
  66.   //update rating
  67.   const indexOfRecordToUpdate=beer.rating.findIndex(x=>x.userRated==user._id);
  68.   const newRating={userRated:user._id,value:rating}
  69.   const copyRating=[...beer.rating]
  70.   const removedOld=copyRating.splice(indexOfRecordToUpdate,1)
  71.   copyRating.push(newRating);
  72.   updatedBeer.rating=copyRating;
  73.  
  74.   const validationErrors=(recordFormValidation(updatedBeer));
  75.   setErrors([...recordFormValidation(updatedBeer)]);
  76.   console.log(validationErrors)
  77.   console.log(errors)
  78.    
  79. //  WHY DO YOU TRIGGER BEFORE STATE IS UPDATED, AAAARGH
  80. if (validationErrors.length<1){      
  81.   beerService.updateBeer(beerId, updatedBeer)
  82.     .then(result=>console.log(result))
  83.      navigate('/');    
  84.   } else{
  85.     console.log(validationErrors)
  86.   }
  87. }
  88.  
  89. const ratingButtons=(
  90.   <div className={styles.rating}>
  91.   {[...Array(5)].map((star, index) => {
  92.   index += 1;
  93.   return (
  94.   <button
  95.   type="button"
  96.   key={index}
  97.   className={  index <= (hover || rating) ? styles.on : styles.off }
  98.   onClick={function(){
  99.   setRating(index);
  100.   }}
  101.   onMouseEnter={() => setHover(index)}
  102.   onMouseLeave={() => setHover(rating)}
  103.   >
  104.   <span>&#127866;</span>
  105.   </button>
  106.   );
  107.   })}
  108.  
  109. </div>
  110. )
  111.  
  112.     return (
  113.   <>
  114.     <form id="beer_form" className={styles.createForm}  onSubmit={onBeerUpdate} method="POST">
  115.        <label className={styles.createLabel}  htmlFor="beerName">Марка:</label>
  116.        <input className={styles.createInput} type="text" id="beerName" name="beerName"
  117.        defaultValue={beer.title}></input>
  118.  
  119.        <label className={styles.createLabel} htmlFor="beerPicture">Изображение:</label>
  120.        <input  className={styles.createInput} type="text" id="beerPicture" name="beerPicture"
  121.        defaultValue={beer.imgUrl}></input>
  122.  
  123.       <label className={styles.createLabel} htmlFor="beerTypes">Тип:</label>
  124.       <select className={styles.createSelect} name="beerTypes" id="beerTypes"
  125.       defaultValue={beer.type}>
  126.         <option value="Тъмна">Тъмна</option>
  127.         <option value="Светла">Светла</option>
  128.         <option value="Вайс">Вайс</option>
  129.        </select>
  130.  
  131.       <label className={styles.createLabel} htmlFor="beerOrigin">Произход:</label>
  132.       <select className={styles.createSelect} name="beerOrigin" id="beerOrigin"
  133.       defaultValue={beer.country}>
  134.         <option value="България">България</option>
  135.         <option value="Внос">Внос</option>
  136.       </select>
  137.  
  138.       <label className={styles.createLabel} htmlFor="alcoholicContent">Алкохолно съдържание:</label>
  139.       <input className={styles.createInput} type="number" name="alcoholicContent" id="alcoholicContent" min="0" step="0.1" max="10"
  140.       defaultValue={beer.alcVol}></input>
  141.  
  142.       {ratingButtons}
  143.       {errors.length>0?<Error errors={errors}/>:""}
  144.       <button type="submit" id="submitBeer">Запази</button>
  145.     </form>    
  146.   </>
  147.     );
  148.   }
  149.  
  150.   export default UpdateRecord;
Advertisement
RAW Paste Data Copied
Advertisement