Эх сурвалжийг харах

useMutation example :godmode:

amenpunk 3 жил өмнө
parent
commit
bce375093c

+ 39 - 32
src/Components/Modal/AgregarManual.js

@@ -12,11 +12,22 @@ import {
 } from '@mui/material';
 
 import { Service } from '../../Utils/HTTP';
+import { useQuery, useMutation, useQueryClient } from 'react-query';
 import useAuth from '../../Auth/useAuth';
 
-
 function Manual(props) {
 
+    const auth = useAuth();
+    const token = auth.getToken();
+
+    const getCategories = async () => {
+        let rest = new Service("/categoria/getAll")
+        return await rest.getQuery(token)
+    }
+
+    const { data } = useQuery('categories', getCategories);
+    const queryClient = useQueryClient();
+
     const NewPlazaSchema = Yup.object().shape({
         nombrepuesto: Yup.string().required('El nombre es requerido').min(5, "El nombre del  puesto debe ser mayor a 5 caracteres").max(100),
         puestosuperior: Yup.number("El puesto superior debe ser un número").required("El puesto es requerido"),
@@ -33,12 +44,16 @@ function Manual(props) {
         setDepartamento(event.target.value);
     };
 
+    const agregarPuesto = async (puesto) => {
+        let rest = new Service('/plaza/save');
+        return await rest.postQuery(puesto, token);
+    }
+
+    const puestoMutation = useMutation(agregarPuesto)
 
-    const [date, setDate] = React.useState(new Date());
-    const auth = useAuth();
-    const token = auth.getToken();
 
-    let { visible, onClose, Complete, categorias } = props
+    const [date, setDate] = React.useState(new Date());
+    let { visible, onClose } = props
 
     const formik = useFormik({
         initialValues: {
@@ -55,22 +70,14 @@ function Manual(props) {
             fields['areadeptoplz_id'] = 1;
             fields['id'] = -1;
 
-            let Rest = new Service('/plaza/save');
-
-            Rest
-                .post(fields, token)
-                .then(_ => {
+            puestoMutation.mutate(fields,{
+                onSuccess:() =>{
+                    setOpen(false)
                     resetForm();
-                    Complete(true, "Puesto agregado exitosamente");
                     onClose();
-                    setOpen(false)
-                })
-                .catch(err => {
-                    console.error(err)
-                    Complete(false, "Ocurrio un error intentalo nuevamente");
-                    setOpen(false)
-                })
-
+                    queryClient.invalidateQueries('puestos')
+                }
+            })
         },
         validationSchema: NewPlazaSchema,
     });
@@ -98,7 +105,7 @@ function Manual(props) {
                                     {...getFieldProps('nombrepuesto')}
                                     error={Boolean(touched.nombrepuesto && errors.nombrepuesto)}
                                     helperText={touched.nombrepuesto && errors.nombrepuesto}
-                                />
+                                    />
 
                                 <TextField
                                     label="Puesto Superior"
@@ -106,7 +113,7 @@ function Manual(props) {
                                     {...getFieldProps('puestosuperior')}
                                     error={Boolean(touched.puestosuperior && errors.puestosuperior)}
                                     helperText={touched.puestosuperior && errors.puestosuperior}
-                                />
+                                    />
 
                             </Stack>
                             <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
@@ -120,14 +127,14 @@ function Manual(props) {
                                         {...getFieldProps('aredepto')}
                                         error={Boolean(touched.aredepto && errors.aredepto)} >
                                         {
-                                            categorias ?
-                                                categorias.map(cate => {
-                                                    return (
-                                                        <MenuItem key={cate.id} value={cate.id}>{cate.nombre}</MenuItem>
-                                                    )
-                                                })
-                                                : <MenuItem>Null</MenuItem>
-                                        }
+                                        data ?
+                                            data.data.map(cate => {
+                                                return (
+                                                    <MenuItem key={cate.id} value={cate.id}>{cate.nombre}</MenuItem>
+                                                )
+                                            })
+                                            : <MenuItem>Null</MenuItem>
+                                    }
                                     </Select>
                                 </FormControl>
 
@@ -147,8 +154,8 @@ function Manual(props) {
                                                 label="Fecha Creación"
                                                 fullWidth
                                                 {...params}
-                                            />}
-                                    />
+                                                />}
+                                        />
                                 </LocalizationProvider>
 
                             </Stack>
@@ -165,7 +172,7 @@ function Manual(props) {
                                     {...getFieldProps('notas')}
                                     error={Boolean(touched.notas && errors.notas)}
                                     helperText={touched.notas && errors.notas}
-                                />
+                                    />
                             </Stack>
                         </Stack>
 

+ 3 - 3
src/Components/Puestos/Card.jsx

@@ -10,7 +10,7 @@ import QA from '../../Images/puesto.jpg'
 
 export function PuestoCard(props) {
 
-    let {nombre, description} = props.plaza
+    let { nombrepuesto, notas} = props.plaza
     let {edit, suprime, show, set} = props.operations
 
     return (
@@ -23,10 +23,10 @@ export function PuestoCard(props) {
                 />
             <CardContent>
                 <Typography gutterBottom variant="h5" component="div">
-                    {nombre}
+                    {nombrepuesto}
                 </Typography>
                 <Typography variant="body2" color="text.secondary">
-                    {description}
+                    {notas}
                     Lizards are a widespread group of squamate reptiles, with over 6,000
                     species, ranging across all continents except Antarctica
                 </Typography>

+ 22 - 22
src/Components/Puestos/GridMode.jsx

@@ -3,34 +3,34 @@ import { Grow } from '@mui/material';
 import { Col } from 'react-bootstrap'
 import { PuestoCard } from './Card';
 
-export function GridMode(props){
+export function GridMode(props) {
 
-    let { setPuesto,setEdit, setDelete, setShow ,data, index, showing} = props;
+    let { setPuesto, setEdit, setDelete, setShow, data, index, showing } = props;
 
-    const op ={
-        set :setPuesto,
-        edit : setEdit,
-        suprime : setDelete,
-        show : setShow,
+    const op = {
+        set: setPuesto,
+        edit: setEdit,
+        suprime: setDelete,
+        show: setShow,
     }
 
-    return(
-        <React.Fragment> 
+    return (
+        <React.Fragment>
             {
-                data.length && showing === 'grid' ? 
-                data[index].map( plaza => {
-                        return(
-                        <Grow in={true} style={{ transformOrigin: '0 0 0' }} timeout={500} key={plaza.id} >
-                            <Col lg="4" md="6" sm="6" xs="12" >
-                                <div style={{ padding: 15 }}>
-                                    <PuestoCard 
-                                        plaza={plaza}
-                                        operations={op} />
-                                </div>
-                            </Col>
-                        </Grow>
+                data.length && showing === 'grid' ?
+                    data[index].map(plaza => {
+                        return (
+                            <Grow in={true} style={{ transformOrigin: '0 0 0' }} timeout={500} key={plaza.id} >
+                                <Col lg="4" md="6" sm="6" xs="12" >
+                                    <div style={{ padding: 15 }}>
+                                        <PuestoCard
+                                            plaza={plaza}
+                                            operations={op} />
+                                    </div>
+                                </Col>
+                            </Grow>
                         )
-                }) : <div></div>
+                    }) : <div></div>
             }
         </React.Fragment>
     )

+ 25 - 88
src/Pages/Puestos.jsx

@@ -1,7 +1,8 @@
 import React, { useState, useCallback } from 'react';
 import { Row, Col } from 'react-bootstrap'
 
-import toast, { Toaster } from 'react-hot-toast';
+import { Toaster } from 'react-hot-toast';
+// import toast, { Toaster } from 'react-hot-toast';
 
 import {
     ToggleButton, ToggleButtonGroup, Box,
@@ -12,7 +13,7 @@ import { ViewList as ViewListIcon, ViewModule as ViewModuleIcon, } from '@mui/ic
 
 import { default as useAuth } from '../Auth/useAuth';
 import { Service } from '../Utils/HTTP';
-// import { Divide } from '../Utils/Paginate';
+import { Divide } from '../Utils/Paginate';
 
 import Express from '../Components/Modal/AgregarExpress';
 import Manual from '../Components/Modal/AgregarManual';
@@ -34,81 +35,17 @@ export function Puestos() {
 
     const auth = useAuth();
     const token = auth.getToken();
+    const [page, setPage] = useState(1);
 
-    const Complete = useCallback((status, message) => {
-
-        if (!status) {
-            return toast.error(message)
-        }
-
-        let rest = new Service("/plaza/getall")
-        rest
-            .get(token)
-            .then(({ data }) => {
-                return data;
-                // let entries = data.map(e => {
-                //     return {
-                //         nombre: e.nombrepuesto,
-                //         description: e.notas,
-                //         id: e.id,
-                //         created: e.create_day,
-                //         data: e
-                //     };
-                // })
-                //setData(Divide(entries))
-            })
-            .catch((error) => {
-                console.log('error fetching data  ', error);
-            })
-
-        toast.success(message)
-    },[token])
-
-    const getAll = useCallback(async () => {
+    const getAll = async () => {
         let rest = new Service("/plaza/getall")
         let response =  await rest.getQuery(token); 
         return response;
-    },[token])
-
-    useCallback(() => {
-        let rest = new Service("/categoria/getAll")
-        rest
-            .get(token)
-            .then(({ data }) => {
-                console.log(data)
-                setCategorias(data);
-            })
-            .catch((error) => {
-                console.log('error fetching data  ', error);
-                return error;
-            })
-
-    },[token])
-
-    const { isLoading, error, data } = useQuery('puestos', getAll);
-    console.log( isLoading, error, data )
-
-    const [page, setPage] = useState(1);
-    const [categorias, setCategorias] = useState([]);
+    }
 
+    const { isLoading, error, data : result } = useQuery('puestos', getAll);
     const changePage = useCallback((_, value) => setPage(value),[]);
-
-    // useEffect(() => {
-    //     // let entries = data.map( e => {
-    //     //     return {
-    //     //         nombre : e.nombrepuesto,
-    //     //         description : e.notas,
-    //     //         id : e.id,
-    //     //         created: e.create_day,
-    //     //         data: e
-    //     //     };
-    //     // })
-    //     // setData(Divide(entries))
-    // }, [])
-
-    // const [alignment, setAlignment] = React.useState('list');
     const [alignment, setAlignment] = React.useState('grid');
-
     const handleChange = useCallback((_event, newAlignment) => setAlignment(newAlignment),[])
 
     const children = [
@@ -127,15 +64,21 @@ export function Puestos() {
     };
 
     let [puesto, setPuesto] = React.useState(false);
-
     let [manual, setManual] = React.useState(false);
     let [expres, setExpress] = React.useState(false);
-
     let [edit, setEdit] = React.useState(false);
     let [del, setDelete] = React.useState(false);
     let [show, setShow] = React.useState(false);
 
-    if (isLoading) return <Loading />
+    if (isLoading){
+        return(
+            <Paper sx={{ mb: 2, padding: 2, height: '100%', minHeight: '95vh' }}>
+                <main id="loading_or_content">
+                    <Loading />
+                </main>
+            </Paper>
+        )
+    } 
 
     if (error) {
         return (
@@ -147,6 +90,8 @@ export function Puestos() {
         )
     }
 
+    const total_items = Divide(result.data).length
+
     return (
         <div className="content-section">
             <div className="main">
@@ -182,10 +127,8 @@ export function Puestos() {
                                 <Row>
                                     <GridMode
                                         showing={alignment}
-                                        data={[]}
-                                        // data={data}
-                                        index={0}
-                                        // index={page - 1}
+                                        data={Divide( result.data )}
+                                        index={page - 1}
                                         setPuesto={setPuesto}
                                         setEdit={setEdit}
                                         setDelete={setDelete}
@@ -197,10 +140,8 @@ export function Puestos() {
                                 <Row>
                                     <ListMode
                                         showing={alignment}
-                                        data={[]}
-                                        // data={data}
-                                        // index={page - 1}
-                                        index={0}
+                                        data={Divide( result.data )}
+                                        index={page - 1}
                                         setPuesto={setPuesto}
                                         setEdit={setEdit}
                                         setDelete={setDelete}
@@ -219,23 +160,19 @@ export function Puestos() {
                                 siblingCount={2}
                                 boundaryCount={2}
                                 shape='rounded'
-                                // count={data.length}
-                                count={0}
+                                count={total_items}
                                 page={page}
                                 onChange={changePage}
                             />
-
-
                         </div>
-
                     </Paper>
                 </Box>
             </div>
 
             <Express setExpress={setExpress} visible={expres} onClose={() => setExpress(false)} />
-            <Manual categorias={categorias} Complete={Complete} visible={manual} onClose={() => setManual(false)} />
+            <Manual visible={manual} onClose={() => setManual(false)} />
 
-            <Editar categorias={categorias} Complete={Complete} puesto={puesto} visible={edit} onClose={() => setEdit(false)} />
+            <Editar puesto={puesto} visible={edit} onClose={() => setEdit(false)} />
             <Eliminar puesto={puesto} visible={del} onClose={() => setDelete(false)} />
             <Mostrar puesto={puesto} visible={show} onClose={() => setShow(false)} />
 

+ 28 - 0
src/Utils/HTTP.js

@@ -65,6 +65,34 @@ export class Service {
 
     }
     
+    async postQuery(body, token){
+
+        if(!token){
+            return await axios({
+                method: "POST",
+                url: this.url,
+                headers:{
+                    'Content-Type': 'application/json',
+                },
+                data :body
+            })
+        }
+
+
+        const MyHeaders ={
+            'Authorization': 'Bearer '+ token,
+        }
+        
+        return await axios({
+            method: "POST",
+            url : this.url,
+            headers: MyHeaders,
+            data: body
+        })
+
+
+    }
+    
     async put(body, token){
 
         if(!token){

+ 1 - 1
src/Utils/Paginate.js

@@ -1,5 +1,5 @@
 export function Divide(arregloOriginal){
-    const LONGITUD_PEDAZOS = 9;
+    const LONGITUD_PEDAZOS = 6;
     let arregloDeArreglos = [];
     for (let i = 0; i < arregloOriginal.length; i += LONGITUD_PEDAZOS) {
         let pedazo = arregloOriginal.slice(i, i + LONGITUD_PEDAZOS);