Facebook
From magnus, 3 Years ago, written in JavaScript.
Embed
Download Paste or View Raw
Hits: 63
  1. import React, { useState, useEffect } from 'react';
  2. import * as Yup from 'yup';
  3. import { Formik } from 'formik';
  4. import _ from 'lodash';
  5. import { useDispatch, useSelector } from 'react-redux';
  6. import { getMenus } from 'src/slices/menu';
  7. import useAuth from 'src/hooks/useAuth';
  8.  
  9. import {
  10.   Box,
  11.   Button,
  12.   Card,
  13.   CardContent,
  14.   CardHeader,
  15.   Checkbox,
  16.   CircularProgress,
  17.   Divider,
  18.   FormHelperText,
  19.   Grid,
  20.   Link,
  21.   TextField,
  22.   Typography
  23. } from '@material-ui/core';
  24. import { Alert } from '@material-ui/lab';
  25. import wait from 'src/utils/wait';
  26. import axios from 'axios';
  27.  
  28. const CardForm = ({ item, index, menuItem, subMenu }) => {
  29.   const [isAlertVisible, setAlertVisible] = useState(false);
  30.   const [response, setResponse] = useState({});
  31.   const dispatch = useDispatch();
  32.   const { establishment } = useAuth();
  33.  
  34.  
  35.   useEffect(() => {
  36.     console.log('running....')
  37.     dispatch(getMenus(establishment._id));
  38.   }, []);
  39.  
  40.   const sendEdit = async values => {
  41.     console.log(values, 'dette skal sendes inn');
  42.     const menu = _.cloneDeep(menuItem);
  43.     let update = menu.sections[subMenu.index].items.splice([index], 1, values);
  44.     const accessToken = window.localStorage.getItem('accessToken');
  45.     const config = {
  46.       headers: { Auhorization: `Bearer ${accessToken}` }
  47.     };
  48.     const data = await axios
  49.       .put(`http://localhost:5000/api/menus/${menu._id}`, menu, config)
  50.       .then(result => {
  51.         setResponse(result);
  52.         // Update state
  53.         dispatch(getMenus(establishment._id));
  54.        
  55.        
  56.  
  57.         return result;
  58.       })
  59.       .catch(err => {
  60.         setResponse(err);
  61.         return new Promise(err);
  62.       });
  63.     return data;
  64.   };
  65.  
  66.   return (
  67.     <Formik
  68.       initialValues={{
  69.         price: item.price,
  70.         name: item.name,
  71.         id: item.id,
  72.         description: item.description,
  73.         // policy: false,
  74.         submit: null
  75.       }}
  76.       validationSchema={Yup.object().shape({
  77.         price: Yup.string().required('Required'),
  78.         name: Yup.string().required('Required'),
  79.         id: Yup.string().required('Required'),
  80.         description: Yup.string()
  81.           .min(3, 'Må være minst 3 bokstaver')
  82.           .max(255)
  83.           .required('Required')
  84.         // policy: Yup.boolean().oneOf([true], 'This field must be checked')
  85.       })}
  86.       onSubmit={async (
  87.         values,
  88.         { resetForm, setErrors, setStatus, setSubmitting }
  89.       ) => {
  90.         try {
  91.           // NOTE: Make API request
  92.           // await wait(1000);
  93.           await sendEdit(values);
  94.           resetForm();
  95.           setStatus({ success: true });
  96.           setSubmitting(false);
  97.           setAlertVisible(true);
  98.           resetForm();
  99.         } catch (err) {
  100.           console.error(err);
  101.           setStatus({ success: false });
  102.           setErrors({ submit: err.message });
  103.           setSubmitting(false);
  104.         }
  105.       }}
  106.     >
  107.       {({
  108.         errors,
  109.         handleBlur,
  110.         handleChange,
  111.         handleSubmit,
  112.         isSubmitting,
  113.         touched,
  114.         values
  115.       }) => (
  116.         <Card>
  117.           <CardHeader title={`Rediger ${item.name}`} />
  118.           <Divider />
  119.           <CardContent>
  120.             {isAlertVisible && (
  121.               <Box mb={3}>
  122.                 <Alert
  123.                   onClose={() => setAlertVisible(false)}
  124.                   severity={response.status ? 'success' : 'error'}
  125.                 >
  126.                   {response.status === 200
  127.                     ? `Flott! Da er den oppdatert.`
  128.                     : 'Beklager, det har skjedd en feil. Din beskjed er ikke registrert'}
  129.                 </Alert>
  130.               </Box>
  131.             )}
  132.             {isSubmitting ? (
  133.               <Box display="flex" justifyContent="center" my={5}>
  134.                 <CircularProgress />
  135.               </Box>
  136.             ) : (
  137.               <form onSubmit={handleSubmit}>
  138.                 <Grid container spacing={2}>
  139.                   <Grid item md={6} xs={12}>
  140.                     <TextField
  141.                       error={Boolean(touched.name && errors.name)}
  142.                       fullWidth
  143.                       helperText={touched.name && errors.name}
  144.                       label="Navn"
  145.                       name="name"
  146.                       onBlur={handleBlur}
  147.                       onChange={handleChange}
  148.                       value={values.name}
  149.                       variant="outlined"
  150.                     />
  151.                   </Grid>
  152.                   <Grid item md={6} xs={12}>
  153.                     <TextField
  154.                       error={Boolean(touched.id && errors.id)}
  155.                       fullWidth
  156.                       helperText={touched.id && errors.id}
  157.                       label="Meny nummer"
  158.                       name="id"
  159.                       onBlur={handleBlur}
  160.                       onChange={handleChange}
  161.                       value={values.id}
  162.                       variant="outlined"
  163.                     />
  164.                   </Grid>
  165.                 </Grid>
  166.                 <Box mt={2}>
  167.                   <TextField
  168.                     error={Boolean(touched.price && errors.price)}
  169.                     fullWidth
  170.                     helperText={touched.price && errors.price}
  171.                     label="Pris"
  172.                     name="price"
  173.                     onBlur={handleBlur}
  174.                     onChange={handleChange}
  175.                     type="price"
  176.                     value={values.price}
  177.                     variant="outlined"
  178.                   />
  179.                 </Box>
  180.                 <Box mt={2}>
  181.                   <TextField
  182.                     error={Boolean(touched.description && errors.description)}
  183.                     fullWidth
  184.                     helperText={touched.description && errors.description}
  185.                     label="Beskrivelse"
  186.                     name="description"
  187.                     onBlur={handleBlur}
  188.                     onChange={handleChange}
  189.                     type="description"
  190.                     value={values.description}
  191.                     variant="outlined"
  192.                   />
  193.                 </Box>
  194.                 {/* <Box alignItems="center" display="flex" mt={2} ml={-1}>
  195.                   <Checkbox
  196.                     checked={values.policy}
  197.                     name="policy"
  198.                     onChange={handleChange}
  199.                   />
  200.                   <Typography variant="body2" color="textSecondary">
  201.                     I have read the{' '}
  202.                     <Link component="a" href="#" color="secondary">
  203.                       Terms and Conditions
  204.                     </Link>
  205.                   </Typography>
  206.                 </Box>
  207.                 {Boolean(touched.policy && errors.policy) && (
  208.                   <FormHelperText error>{errors.policy}</FormHelperText>
  209.                 )} */}
  210.                 <Box mt={2}>
  211.                   <Button
  212.                     color="secondary"
  213.                     disabled={isSubmitting}
  214.                     fullWidth
  215.                     size="large"
  216.                     type="submit"
  217.                     variant="contained"
  218.                   >
  219.                     Lagre
  220.                   </Button>
  221.                 </Box>
  222.               </form>
  223.             )}
  224.           </CardContent>
  225.         </Card>
  226.       )}
  227.     </Formik>
  228.   );
  229. };
  230.  
  231. export default CardForm;
  232.