@visns-studio/visns-components 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,101 @@
1
+ import _ from 'lodash';
2
+ import axios from 'axios';
3
+ import { trackPromise } from 'react-promise-tracker';
4
+ import { toast } from 'react-toastify';
5
+ import parse from 'html-react-parser';
6
+
7
+ const CustomFetch = (
8
+ url,
9
+ method,
10
+ formData,
11
+ successCallback = null,
12
+ errorCallback = null
13
+ ) => {
14
+ let baseUrl = '';
15
+ let body;
16
+ let headers = {};
17
+ let options = {};
18
+
19
+ if (method.toUpperCase() === 'PUT' || method.toUpperCase() === 'PATCH') {
20
+ body = {
21
+ ...body,
22
+ _method: method,
23
+ };
24
+ }
25
+
26
+ body = JSON.stringify(formData);
27
+ headers = {
28
+ ...headers,
29
+ 'Content-Type': 'application/json',
30
+ };
31
+
32
+ options = {
33
+ method: method,
34
+ data: body,
35
+ headers: headers,
36
+ url: baseUrl + url,
37
+ };
38
+
39
+ trackPromise(
40
+ axios(options).then(
41
+ (result) => {
42
+ if (successCallback) {
43
+ successCallback(result.data);
44
+ } else {
45
+ if (result.data.error === '') {
46
+ toast.success('Data has been updated successfully.');
47
+ } else {
48
+ toast.error(result.data.error);
49
+ }
50
+ }
51
+ },
52
+ (error) => {
53
+ if (
54
+ error.response.hasOwnProperty('data') &&
55
+ error.response.data.hasOwnProperty('message') &&
56
+ error.response.data.message !== ''
57
+ ) {
58
+ if (error.response.data.hasOwnProperty('errors')) {
59
+ let errorMessage = '';
60
+ let errors = error.response.data.errors;
61
+
62
+ Object.keys(errors).forEach((a) => {
63
+ errors[a].forEach((b) => {
64
+ errorMessage += b + '<br />';
65
+ });
66
+ });
67
+
68
+ if (errorCallback) {
69
+ errorCallback(errorMessage);
70
+ } else {
71
+ toast.error(`<div>${parse(errorMessage)}</div>`);
72
+ }
73
+ } else {
74
+ if (
75
+ error.response.data.message ===
76
+ 'CSRF token mismatch.'
77
+ ) {
78
+ window.location.replace('/login');
79
+ } else {
80
+ if (errorCallback) {
81
+ errorCallback(error.response.data.message);
82
+ } else {
83
+ toast.error(
84
+ `<div>${parse(errorMessage)}</div>`
85
+ );
86
+ }
87
+ }
88
+ }
89
+ } else {
90
+ if (errorCallback) {
91
+ errorCallback(error);
92
+ } else {
93
+ toast.error(`<div>${parse(errorMessage)}</div>`);
94
+ }
95
+ }
96
+ }
97
+ )
98
+ );
99
+ };
100
+
101
+ export default CustomFetch;