瀏覽代碼

useMutation example :godmode:

amenpunk 3 年之前
父節點
當前提交
bce375093c

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

12
 } from '@mui/material';
12
 } from '@mui/material';
13
 
13
 
14
 import { Service } from '../../Utils/HTTP';
14
 import { Service } from '../../Utils/HTTP';
15
+import { useQuery, useMutation, useQueryClient } from 'react-query';
15
 import useAuth from '../../Auth/useAuth';
16
 import useAuth from '../../Auth/useAuth';
16
 
17
 
17
-
18
 function Manual(props) {
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
     const NewPlazaSchema = Yup.object().shape({
31
     const NewPlazaSchema = Yup.object().shape({
21
         nombrepuesto: Yup.string().required('El nombre es requerido').min(5, "El nombre del  puesto debe ser mayor a 5 caracteres").max(100),
32
         nombrepuesto: Yup.string().required('El nombre es requerido').min(5, "El nombre del  puesto debe ser mayor a 5 caracteres").max(100),
22
         puestosuperior: Yup.number("El puesto superior debe ser un número").required("El puesto es requerido"),
33
         puestosuperior: Yup.number("El puesto superior debe ser un número").required("El puesto es requerido"),
33
         setDepartamento(event.target.value);
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
     const formik = useFormik({
58
     const formik = useFormik({
44
         initialValues: {
59
         initialValues: {
55
             fields['areadeptoplz_id'] = 1;
70
             fields['areadeptoplz_id'] = 1;
56
             fields['id'] = -1;
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
                     resetForm();
76
                     resetForm();
64
-                    Complete(true, "Puesto agregado exitosamente");
65
                     onClose();
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
         validationSchema: NewPlazaSchema,
82
         validationSchema: NewPlazaSchema,
76
     });
83
     });
98
                                     {...getFieldProps('nombrepuesto')}
105
                                     {...getFieldProps('nombrepuesto')}
99
                                     error={Boolean(touched.nombrepuesto && errors.nombrepuesto)}
106
                                     error={Boolean(touched.nombrepuesto && errors.nombrepuesto)}
100
                                     helperText={touched.nombrepuesto && errors.nombrepuesto}
107
                                     helperText={touched.nombrepuesto && errors.nombrepuesto}
101
-                                />
108
+                                    />
102
 
109
 
103
                                 <TextField
110
                                 <TextField
104
                                     label="Puesto Superior"
111
                                     label="Puesto Superior"
106
                                     {...getFieldProps('puestosuperior')}
113
                                     {...getFieldProps('puestosuperior')}
107
                                     error={Boolean(touched.puestosuperior && errors.puestosuperior)}
114
                                     error={Boolean(touched.puestosuperior && errors.puestosuperior)}
108
                                     helperText={touched.puestosuperior && errors.puestosuperior}
115
                                     helperText={touched.puestosuperior && errors.puestosuperior}
109
-                                />
116
+                                    />
110
 
117
 
111
                             </Stack>
118
                             </Stack>
112
                             <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
119
                             <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
120
                                         {...getFieldProps('aredepto')}
127
                                         {...getFieldProps('aredepto')}
121
                                         error={Boolean(touched.aredepto && errors.aredepto)} >
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
                                     </Select>
138
                                     </Select>
132
                                 </FormControl>
139
                                 </FormControl>
133
 
140
 
147
                                                 label="Fecha Creación"
154
                                                 label="Fecha Creación"
148
                                                 fullWidth
155
                                                 fullWidth
149
                                                 {...params}
156
                                                 {...params}
150
-                                            />}
151
-                                    />
157
+                                                />}
158
+                                        />
152
                                 </LocalizationProvider>
159
                                 </LocalizationProvider>
153
 
160
 
154
                             </Stack>
161
                             </Stack>
165
                                     {...getFieldProps('notas')}
172
                                     {...getFieldProps('notas')}
166
                                     error={Boolean(touched.notas && errors.notas)}
173
                                     error={Boolean(touched.notas && errors.notas)}
167
                                     helperText={touched.notas && errors.notas}
174
                                     helperText={touched.notas && errors.notas}
168
-                                />
175
+                                    />
169
                             </Stack>
176
                             </Stack>
170
                         </Stack>
177
                         </Stack>
171
 
178
 

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

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

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

3
 import { Col } from 'react-bootstrap'
3
 import { Col } from 'react-bootstrap'
4
 import { PuestoCard } from './Card';
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
         </React.Fragment>
35
         </React.Fragment>
36
     )
36
     )

+ 25 - 88
src/Pages/Puestos.jsx

1
 import React, { useState, useCallback } from 'react';
1
 import React, { useState, useCallback } from 'react';
2
 import { Row, Col } from 'react-bootstrap'
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
 import {
7
 import {
7
     ToggleButton, ToggleButtonGroup, Box,
8
     ToggleButton, ToggleButtonGroup, Box,
12
 
13
 
13
 import { default as useAuth } from '../Auth/useAuth';
14
 import { default as useAuth } from '../Auth/useAuth';
14
 import { Service } from '../Utils/HTTP';
15
 import { Service } from '../Utils/HTTP';
15
-// import { Divide } from '../Utils/Paginate';
16
+import { Divide } from '../Utils/Paginate';
16
 
17
 
17
 import Express from '../Components/Modal/AgregarExpress';
18
 import Express from '../Components/Modal/AgregarExpress';
18
 import Manual from '../Components/Modal/AgregarManual';
19
 import Manual from '../Components/Modal/AgregarManual';
34
 
35
 
35
     const auth = useAuth();
36
     const auth = useAuth();
36
     const token = auth.getToken();
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
         let rest = new Service("/plaza/getall")
41
         let rest = new Service("/plaza/getall")
69
         let response =  await rest.getQuery(token); 
42
         let response =  await rest.getQuery(token); 
70
         return response;
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
     const changePage = useCallback((_, value) => setPage(value),[]);
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
     const [alignment, setAlignment] = React.useState('grid');
48
     const [alignment, setAlignment] = React.useState('grid');
111
-
112
     const handleChange = useCallback((_event, newAlignment) => setAlignment(newAlignment),[])
49
     const handleChange = useCallback((_event, newAlignment) => setAlignment(newAlignment),[])
113
 
50
 
114
     const children = [
51
     const children = [
127
     };
64
     };
128
 
65
 
129
     let [puesto, setPuesto] = React.useState(false);
66
     let [puesto, setPuesto] = React.useState(false);
130
-
131
     let [manual, setManual] = React.useState(false);
67
     let [manual, setManual] = React.useState(false);
132
     let [expres, setExpress] = React.useState(false);
68
     let [expres, setExpress] = React.useState(false);
133
-
134
     let [edit, setEdit] = React.useState(false);
69
     let [edit, setEdit] = React.useState(false);
135
     let [del, setDelete] = React.useState(false);
70
     let [del, setDelete] = React.useState(false);
136
     let [show, setShow] = React.useState(false);
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
     if (error) {
83
     if (error) {
141
         return (
84
         return (
147
         )
90
         )
148
     }
91
     }
149
 
92
 
93
+    const total_items = Divide(result.data).length
94
+
150
     return (
95
     return (
151
         <div className="content-section">
96
         <div className="content-section">
152
             <div className="main">
97
             <div className="main">
182
                                 <Row>
127
                                 <Row>
183
                                     <GridMode
128
                                     <GridMode
184
                                         showing={alignment}
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
                                         setPuesto={setPuesto}
132
                                         setPuesto={setPuesto}
190
                                         setEdit={setEdit}
133
                                         setEdit={setEdit}
191
                                         setDelete={setDelete}
134
                                         setDelete={setDelete}
197
                                 <Row>
140
                                 <Row>
198
                                     <ListMode
141
                                     <ListMode
199
                                         showing={alignment}
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
                                         setPuesto={setPuesto}
145
                                         setPuesto={setPuesto}
205
                                         setEdit={setEdit}
146
                                         setEdit={setEdit}
206
                                         setDelete={setDelete}
147
                                         setDelete={setDelete}
219
                                 siblingCount={2}
160
                                 siblingCount={2}
220
                                 boundaryCount={2}
161
                                 boundaryCount={2}
221
                                 shape='rounded'
162
                                 shape='rounded'
222
-                                // count={data.length}
223
-                                count={0}
163
+                                count={total_items}
224
                                 page={page}
164
                                 page={page}
225
                                 onChange={changePage}
165
                                 onChange={changePage}
226
                             />
166
                             />
227
-
228
-
229
                         </div>
167
                         </div>
230
-
231
                     </Paper>
168
                     </Paper>
232
                 </Box>
169
                 </Box>
233
             </div>
170
             </div>
234
 
171
 
235
             <Express setExpress={setExpress} visible={expres} onClose={() => setExpress(false)} />
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
             <Eliminar puesto={puesto} visible={del} onClose={() => setDelete(false)} />
176
             <Eliminar puesto={puesto} visible={del} onClose={() => setDelete(false)} />
240
             <Mostrar puesto={puesto} visible={show} onClose={() => setShow(false)} />
177
             <Mostrar puesto={puesto} visible={show} onClose={() => setShow(false)} />
241
 
178
 

+ 28 - 0
src/Utils/HTTP.js

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
     async put(body, token){
96
     async put(body, token){
69
 
97
 
70
         if(!token){
98
         if(!token){

+ 1 - 1
src/Utils/Paginate.js

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