Browse Source

useMutation example :godmode:

amenpunk 2 years ago
parent
commit
bce375093c

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

@@ -12,11 +12,22 @@ import {
12 12
 } from '@mui/material';
13 13
 
14 14
 import { Service } from '../../Utils/HTTP';
15
+import { useQuery, useMutation, useQueryClient } from 'react-query';
15 16
 import useAuth from '../../Auth/useAuth';
16 17
 
17
-
18 18
 function Manual(props) {
19 19
 
20
+    const auth = useAuth();
21
+    const token = auth.getToken();
22
+
23
+    const getCategories = async () => {
24
+        let rest = new Service("/categoria/getAll")
25
+        return await rest.getQuery(token)
26
+    }
27
+
28
+    const { data } = useQuery('categories', getCategories);
29
+    const queryClient = useQueryClient();
30
+
20 31
     const NewPlazaSchema = Yup.object().shape({
21 32
         nombrepuesto: Yup.string().required('El nombre es requerido').min(5, "El nombre del  puesto debe ser mayor a 5 caracteres").max(100),
22 33
         puestosuperior: Yup.number("El puesto superior debe ser un número").required("El puesto es requerido"),
@@ -33,12 +44,16 @@ function Manual(props) {
33 44
         setDepartamento(event.target.value);
34 45
     };
35 46
 
47
+    const agregarPuesto = async (puesto) => {
48
+        let rest = new Service('/plaza/save');
49
+        return await rest.postQuery(puesto, token);
50
+    }
51
+
52
+    const puestoMutation = useMutation(agregarPuesto)
36 53
 
37
-    const [date, setDate] = React.useState(new Date());
38
-    const auth = useAuth();
39
-    const token = auth.getToken();
40 54
 
41
-    let { visible, onClose, Complete, categorias } = props
55
+    const [date, setDate] = React.useState(new Date());
56
+    let { visible, onClose } = props
42 57
 
43 58
     const formik = useFormik({
44 59
         initialValues: {
@@ -55,22 +70,14 @@ function Manual(props) {
55 70
             fields['areadeptoplz_id'] = 1;
56 71
             fields['id'] = -1;
57 72
 
58
-            let Rest = new Service('/plaza/save');
59
-
60
-            Rest
61
-                .post(fields, token)
62
-                .then(_ => {
73
+            puestoMutation.mutate(fields,{
74
+                onSuccess:() =>{
75
+                    setOpen(false)
63 76
                     resetForm();
64
-                    Complete(true, "Puesto agregado exitosamente");
65 77
                     onClose();
66
-                    setOpen(false)
67
-                })
68
-                .catch(err => {
69
-                    console.error(err)
70
-                    Complete(false, "Ocurrio un error intentalo nuevamente");
71
-                    setOpen(false)
72
-                })
73
-
78
+                    queryClient.invalidateQueries('puestos')
79
+                }
80
+            })
74 81
         },
75 82
         validationSchema: NewPlazaSchema,
76 83
     });
@@ -98,7 +105,7 @@ function Manual(props) {
98 105
                                     {...getFieldProps('nombrepuesto')}
99 106
                                     error={Boolean(touched.nombrepuesto && errors.nombrepuesto)}
100 107
                                     helperText={touched.nombrepuesto && errors.nombrepuesto}
101
-                                />
108
+                                    />
102 109
 
103 110
                                 <TextField
104 111
                                     label="Puesto Superior"
@@ -106,7 +113,7 @@ function Manual(props) {
106 113
                                     {...getFieldProps('puestosuperior')}
107 114
                                     error={Boolean(touched.puestosuperior && errors.puestosuperior)}
108 115
                                     helperText={touched.puestosuperior && errors.puestosuperior}
109
-                                />
116
+                                    />
110 117
 
111 118
                             </Stack>
112 119
                             <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
@@ -120,14 +127,14 @@ function Manual(props) {
120 127
                                         {...getFieldProps('aredepto')}
121 128
                                         error={Boolean(touched.aredepto && errors.aredepto)} >
122 129
                                         {
123
-                                            categorias ?
124
-                                                categorias.map(cate => {
125
-                                                    return (
126
-                                                        <MenuItem key={cate.id} value={cate.id}>{cate.nombre}</MenuItem>
127
-                                                    )
128
-                                                })
129
-                                                : <MenuItem>Null</MenuItem>
130
-                                        }
130
+                                        data ?
131
+                                            data.data.map(cate => {
132
+                                                return (
133
+                                                    <MenuItem key={cate.id} value={cate.id}>{cate.nombre}</MenuItem>
134
+                                                )
135
+                                            })
136
+                                            : <MenuItem>Null</MenuItem>
137
+                                    }
131 138
                                     </Select>
132 139
                                 </FormControl>
133 140
 
@@ -147,8 +154,8 @@ function Manual(props) {
147 154
                                                 label="Fecha Creación"
148 155
                                                 fullWidth
149 156
                                                 {...params}
150
-                                            />}
151
-                                    />
157
+                                                />}
158
+                                        />
152 159
                                 </LocalizationProvider>
153 160
 
154 161
                             </Stack>
@@ -165,7 +172,7 @@ function Manual(props) {
165 172
                                     {...getFieldProps('notas')}
166 173
                                     error={Boolean(touched.notas && errors.notas)}
167 174
                                     helperText={touched.notas && errors.notas}
168
-                                />
175
+                                    />
169 176
                             </Stack>
170 177
                         </Stack>
171 178
 

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

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

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

@@ -3,34 +3,34 @@ import { Grow } from '@mui/material';
3 3
 import { Col } from 'react-bootstrap'
4 4
 import { PuestoCard } from './Card';
5 5
 
6
-export function GridMode(props){
6
+export function GridMode(props) {
7 7
 
8
-    let { setPuesto,setEdit, setDelete, setShow ,data, index, showing} = props;
8
+    let { setPuesto, setEdit, setDelete, setShow, data, index, showing } = props;
9 9
 
10
-    const op ={
11
-        set :setPuesto,
12
-        edit : setEdit,
13
-        suprime : setDelete,
14
-        show : setShow,
10
+    const op = {
11
+        set: setPuesto,
12
+        edit: setEdit,
13
+        suprime: setDelete,
14
+        show: setShow,
15 15
     }
16 16
 
17
-    return(
18
-        <React.Fragment> 
17
+    return (
18
+        <React.Fragment>
19 19
             {
20
-                data.length && showing === 'grid' ? 
21
-                data[index].map( plaza => {
22
-                        return(
23
-                        <Grow in={true} style={{ transformOrigin: '0 0 0' }} timeout={500} key={plaza.id} >
24
-                            <Col lg="4" md="6" sm="6" xs="12" >
25
-                                <div style={{ padding: 15 }}>
26
-                                    <PuestoCard 
27
-                                        plaza={plaza}
28
-                                        operations={op} />
29
-                                </div>
30
-                            </Col>
31
-                        </Grow>
20
+                data.length && showing === 'grid' ?
21
+                    data[index].map(plaza => {
22
+                        return (
23
+                            <Grow in={true} style={{ transformOrigin: '0 0 0' }} timeout={500} key={plaza.id} >
24
+                                <Col lg="4" md="6" sm="6" xs="12" >
25
+                                    <div style={{ padding: 15 }}>
26
+                                        <PuestoCard
27
+                                            plaza={plaza}
28
+                                            operations={op} />
29
+                                    </div>
30
+                                </Col>
31
+                            </Grow>
32 32
                         )
33
-                }) : <div></div>
33
+                    }) : <div></div>
34 34
             }
35 35
         </React.Fragment>
36 36
     )

+ 25 - 88
src/Pages/Puestos.jsx

@@ -1,7 +1,8 @@
1 1
 import React, { useState, useCallback } from 'react';
2 2
 import { Row, Col } from 'react-bootstrap'
3 3
 
4
-import toast, { Toaster } from 'react-hot-toast';
4
+import { Toaster } from 'react-hot-toast';
5
+// import toast, { Toaster } from 'react-hot-toast';
5 6
 
6 7
 import {
7 8
     ToggleButton, ToggleButtonGroup, Box,
@@ -12,7 +13,7 @@ import { ViewList as ViewListIcon, ViewModule as ViewModuleIcon, } from '@mui/ic
12 13
 
13 14
 import { default as useAuth } from '../Auth/useAuth';
14 15
 import { Service } from '../Utils/HTTP';
15
-// import { Divide } from '../Utils/Paginate';
16
+import { Divide } from '../Utils/Paginate';
16 17
 
17 18
 import Express from '../Components/Modal/AgregarExpress';
18 19
 import Manual from '../Components/Modal/AgregarManual';
@@ -34,81 +35,17 @@ export function Puestos() {
34 35
 
35 36
     const auth = useAuth();
36 37
     const token = auth.getToken();
38
+    const [page, setPage] = useState(1);
37 39
 
38
-    const Complete = useCallback((status, message) => {
39
-
40
-        if (!status) {
41
-            return toast.error(message)
42
-        }
43
-
44
-        let rest = new Service("/plaza/getall")
45
-        rest
46
-            .get(token)
47
-            .then(({ data }) => {
48
-                return data;
49
-                // let entries = data.map(e => {
50
-                //     return {
51
-                //         nombre: e.nombrepuesto,
52
-                //         description: e.notas,
53
-                //         id: e.id,
54
-                //         created: e.create_day,
55
-                //         data: e
56
-                //     };
57
-                // })
58
-                //setData(Divide(entries))
59
-            })
60
-            .catch((error) => {
61
-                console.log('error fetching data  ', error);
62
-            })
63
-
64
-        toast.success(message)
65
-    },[token])
66
-
67
-    const getAll = useCallback(async () => {
40
+    const getAll = async () => {
68 41
         let rest = new Service("/plaza/getall")
69 42
         let response =  await rest.getQuery(token); 
70 43
         return response;
71
-    },[token])
72
-
73
-    useCallback(() => {
74
-        let rest = new Service("/categoria/getAll")
75
-        rest
76
-            .get(token)
77
-            .then(({ data }) => {
78
-                console.log(data)
79
-                setCategorias(data);
80
-            })
81
-            .catch((error) => {
82
-                console.log('error fetching data  ', error);
83
-                return error;
84
-            })
85
-
86
-    },[token])
87
-
88
-    const { isLoading, error, data } = useQuery('puestos', getAll);
89
-    console.log( isLoading, error, data )
90
-
91
-    const [page, setPage] = useState(1);
92
-    const [categorias, setCategorias] = useState([]);
44
+    }
93 45
 
46
+    const { isLoading, error, data : result } = useQuery('puestos', getAll);
94 47
     const changePage = useCallback((_, value) => setPage(value),[]);
95
-
96
-    // useEffect(() => {
97
-    //     // let entries = data.map( e => {
98
-    //     //     return {
99
-    //     //         nombre : e.nombrepuesto,
100
-    //     //         description : e.notas,
101
-    //     //         id : e.id,
102
-    //     //         created: e.create_day,
103
-    //     //         data: e
104
-    //     //     };
105
-    //     // })
106
-    //     // setData(Divide(entries))
107
-    // }, [])
108
-
109
-    // const [alignment, setAlignment] = React.useState('list');
110 48
     const [alignment, setAlignment] = React.useState('grid');
111
-
112 49
     const handleChange = useCallback((_event, newAlignment) => setAlignment(newAlignment),[])
113 50
 
114 51
     const children = [
@@ -127,15 +64,21 @@ export function Puestos() {
127 64
     };
128 65
 
129 66
     let [puesto, setPuesto] = React.useState(false);
130
-
131 67
     let [manual, setManual] = React.useState(false);
132 68
     let [expres, setExpress] = React.useState(false);
133
-
134 69
     let [edit, setEdit] = React.useState(false);
135 70
     let [del, setDelete] = React.useState(false);
136 71
     let [show, setShow] = React.useState(false);
137 72
 
138
-    if (isLoading) return <Loading />
73
+    if (isLoading){
74
+        return(
75
+            <Paper sx={{ mb: 2, padding: 2, height: '100%', minHeight: '95vh' }}>
76
+                <main id="loading_or_content">
77
+                    <Loading />
78
+                </main>
79
+            </Paper>
80
+        )
81
+    } 
139 82
 
140 83
     if (error) {
141 84
         return (
@@ -147,6 +90,8 @@ export function Puestos() {
147 90
         )
148 91
     }
149 92
 
93
+    const total_items = Divide(result.data).length
94
+
150 95
     return (
151 96
         <div className="content-section">
152 97
             <div className="main">
@@ -182,10 +127,8 @@ export function Puestos() {
182 127
                                 <Row>
183 128
                                     <GridMode
184 129
                                         showing={alignment}
185
-                                        data={[]}
186
-                                        // data={data}
187
-                                        index={0}
188
-                                        // index={page - 1}
130
+                                        data={Divide( result.data )}
131
+                                        index={page - 1}
189 132
                                         setPuesto={setPuesto}
190 133
                                         setEdit={setEdit}
191 134
                                         setDelete={setDelete}
@@ -197,10 +140,8 @@ export function Puestos() {
197 140
                                 <Row>
198 141
                                     <ListMode
199 142
                                         showing={alignment}
200
-                                        data={[]}
201
-                                        // data={data}
202
-                                        // index={page - 1}
203
-                                        index={0}
143
+                                        data={Divide( result.data )}
144
+                                        index={page - 1}
204 145
                                         setPuesto={setPuesto}
205 146
                                         setEdit={setEdit}
206 147
                                         setDelete={setDelete}
@@ -219,23 +160,19 @@ export function Puestos() {
219 160
                                 siblingCount={2}
220 161
                                 boundaryCount={2}
221 162
                                 shape='rounded'
222
-                                // count={data.length}
223
-                                count={0}
163
+                                count={total_items}
224 164
                                 page={page}
225 165
                                 onChange={changePage}
226 166
                             />
227
-
228
-
229 167
                         </div>
230
-
231 168
                     </Paper>
232 169
                 </Box>
233 170
             </div>
234 171
 
235 172
             <Express setExpress={setExpress} visible={expres} onClose={() => setExpress(false)} />
236
-            <Manual categorias={categorias} Complete={Complete} visible={manual} onClose={() => setManual(false)} />
173
+            <Manual visible={manual} onClose={() => setManual(false)} />
237 174
 
238
-            <Editar categorias={categorias} Complete={Complete} puesto={puesto} visible={edit} onClose={() => setEdit(false)} />
175
+            <Editar puesto={puesto} visible={edit} onClose={() => setEdit(false)} />
239 176
             <Eliminar puesto={puesto} visible={del} onClose={() => setDelete(false)} />
240 177
             <Mostrar puesto={puesto} visible={show} onClose={() => setShow(false)} />
241 178
 

+ 28 - 0
src/Utils/HTTP.js

@@ -65,6 +65,34 @@ export class Service {
65 65
 
66 66
     }
67 67
     
68
+    async postQuery(body, token){
69
+
70
+        if(!token){
71
+            return await axios({
72
+                method: "POST",
73
+                url: this.url,
74
+                headers:{
75
+                    'Content-Type': 'application/json',
76
+                },
77
+                data :body
78
+            })
79
+        }
80
+
81
+
82
+        const MyHeaders ={
83
+            'Authorization': 'Bearer '+ token,
84
+        }
85
+        
86
+        return await axios({
87
+            method: "POST",
88
+            url : this.url,
89
+            headers: MyHeaders,
90
+            data: body
91
+        })
92
+
93
+
94
+    }
95
+    
68 96
     async put(body, token){
69 97
 
70 98
         if(!token){

+ 1 - 1
src/Utils/Paginate.js

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