-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNormalAdvancedData.json
More file actions
227 lines (227 loc) · 230 KB
/
NormalAdvancedData.json
File metadata and controls
227 lines (227 loc) · 230 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
{
"status": "ok",
"feed": {
"url": "https://medium.com/feed/@sabesan96",
"title": "Stories by Sabesan Sathananthan on Medium",
"link": "https://medium.com/@sabesan96?source=rss-b255948cc1f5------2",
"author": "",
"description": "Stories by Sabesan Sathananthan on Medium",
"image": "https://cdn-images-1.medium.com/fit/c/150/150/1*dwqu7TGEPXw30P9Z9YNgfA.jpeg"
},
"items": [
{
"title": "Why and How to Use Absolute Imports in React",
"pubDate": "2021-10-08 10:45:44",
"link": "https://javascript.plainenglish.io/why-and-how-to-use-absolute-imports-in-react-d5b52f24d53c?source=rss-b255948cc1f5------2",
"guid": "https://medium.com/p/d5b52f24d53c",
"author": "Sabesan Sathananthan",
"thumbnail": "https://cdn-images-1.medium.com/max/1024/1*jgQN6rI0OJB_OXgVTgOwLw.jpeg",
"description": "\n<h4>Front End</h4>\n<h4>An easy way to maintain clean code in React</h4>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*jgQN6rI0OJB_OXgVTgOwLw.jpeg\"><figcaption>Photo by <a href=\"https://www.pexels.com/@ketut-subiyanto?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels\">Ketut Subiyanto</a> from <a href=\"https://www.pexels.com/photo/crop-faceless-man-packing-box-with-scotch-tape-4246109/?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels\">Pexels</a></figcaption></figure><p>Using absolute imports to better organize your React project is a great way. Relative imports are hard to follow and break during refactoring. Absolute imports manage your project easier as it grows. Forget long relative imports after this article. This is my 40th Medium article.</p>\n<h3>The Problem</h3>\n<p>What if your project’s folder structure is complex, and you need to <strong>go up</strong> in it? Inside of your components, you have imports that look like the below example with relative imports.</p>\n<pre>import {MyComponent} from ‘../../../../components/MyComponent’;</pre>\n<p>You can break the above import by changing the path of the component from which you are importing your MyComponent. Let’s assume you decide to move MyComponent into its own folder. Then you would need to update all of your imports in your project and add one extra ../ to all of your imports. Relative imports has some more problems.</p>\n<ul>\n<li>Pretty hard to refactor</li>\n<li>It becomes worse as you get further deeper into it.</li>\n<li>You need to change the entire codebase if you need to extract the code to be used externally as an NPM module.</li>\n</ul>\n<h3>Absolute Imports</h3>\n<p>By using absolute imports, you can alias some folders to a name like below:</p>\n<pre>import {MyComponent} from ‘components/MyComponent’;</pre>\n<p>Absolute imports have some advantages.</p>\n<ul>\n<li>There is no ../../../../hell. Therefore easier to type out the imports.</li>\n<li>Easily copy-paste the code with imports into another file in the project and not have to tinker with import paths.</li>\n<li>It is short and sweet</li>\n</ul>\n<p>The below example is a file with Relative imports.</p>\n<a href=\"https://medium.com/media/bf07582509895a0421291b5c22db5b93/href\">https://medium.com/media/bf07582509895a0421291b5c22db5b93/href</a><p>Make the imports in the above file prettier.</p>\n<a href=\"https://medium.com/media/f50a23cf68a84b3a75257aca796260ae/href\">https://medium.com/media/f50a23cf68a84b3a75257aca796260ae/href</a><p>Therefore, how can you use absolute imports with ReactJs?</p>\n<h4>Using TypeScript</h4>\n<p>If you need to set up absolute imports in your Typescript application add/update your tsconfig.json file in the root directory of the project. Then you need to update the compiler option baseUrl in the file.</p>\n<a href=\"https://medium.com/media/94d143b8d97ef92279a8442c500e4c56/href\">https://medium.com/media/94d143b8d97ef92279a8442c500e4c56/href</a><h4>Using JavaScript</h4>\n<p>Setting up absolute imports to Typescript and setting up absolute imports to JavaScript is pretty much the same process. Create the jsconfig.json file in the root directory of the project. Then you need to update the following snippet.</p>\n<a href=\"https://medium.com/media/b900ae2e75d9c9321443dfe726867272/href\">https://medium.com/media/b900ae2e75d9c9321443dfe726867272/href</a><p>Now you can import your components like this.</p>\n<pre>import {MyComponent} from ‘components/MyComponent’;</pre>\n<p>You can also use the compiler option paths as well. Perhaps you want to alias your component folder. For that, you need to set up your tsconfig.json, or jsconfig.json as shown in below:</p>\n<pre>{<br> \"compilerOptions\": {<br> \"baseUrl\": \"./\",<br> \"paths\": {<br> \"@component/*\": [\"src/components/*\"],<br> }<br> }<br>}</pre>\n<p>Now you can import the components from your component folder like this:</p>\n<pre>import {MyComponent} from ‘@component/MyComponent’;</pre>\n<p>is that enough?</p>\n<p>Well, no… You need to make your IDE smart to understand absolute imports in your files. Here I am going to mention the progress for the top 2 IDEs. Those are VS Code and WebStrom.</p>\n<h4>For VS Code</h4>\n<p>VS Code is smart enough to understand the tsconfig.json, or jsconfig.json file. Intellisense and jump-to-source are just working fine with absolute imports.</p>\n<p>Therefore, you can follow the above process.</p>\n<h4>For WebStrom / IntelliJ Idea</h4>\n<p>Select the src folder in the project window and right-click on it. Select the option <strong>Mark Directory as</strong> and then select the <strong>Resources Root</strong> option.</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/744/1*1QCjtXr7W8tAS97Etkna_w.png\"></figure><p>Now go to <strong>Settings</strong> -> <strong>Editor -</strong>> <strong>Code Style</strong> -> <strong>JavaScript </strong>and<strong> </strong>select the <strong>Imports</strong> tab. Then check the <strong>Use paths relative to the project, resource or sources roots</strong>.</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*VhExpM1Kx5SaHMvuIyAeHg.png\"></figure><p>Now WebStrom knows where the absolute imports are pointing. There won’t no warnings and autocomplete/ jump-to-source will work. This means the auto-import mechanism uses absolute imports.</p>\n<p>If you are a strict developer like me, use something like Airbnb’s ESLint config.</p>\n<h4>With ESLint</h4>\n<p>Create React App also has an ESLint setup but it has a minimal set of rules. <a href=\"https://github.com/benmosher/eslint-plugin-import\">eslint-plugin-import</a> is used by Airbnb and this plugin checks undefined imports. When you are going to use Airbnb’s ESLint config it will give you the error shown below:</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/592/1*7w-nu2REGmEs3V4-1dNcXw.png\"></figure><p>You can fix the error by add settings prop in your ESLint config. That setting prop point that your imports might be relative to src folder. Therefore, you need to add update your ESLint config in .eslintrc file like this:</p>\n<a href=\"https://medium.com/media/d608ef6ca698cb7586d1e89fb901eecf/href\">https://medium.com/media/d608ef6ca698cb7586d1e89fb901eecf/href</a><p>You don’t need to install any NPM modules to avoid the ESLint error, add the settings prop is enough.</p>\n<h4>By Convention</h4>\n<p>Absolute imports have been possible for a long time with Webpack. When you are naming your aliased folder, you need to use PascalCase/CamelCase because it is the convention follow in the <a href=\"https://webpack.js.org/configuration/resolve/#resolvealias\">Webpack</a>.</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/700/1*SsTWqQeNRLM8ReY5PBPK8w.png\"></figure><h3>Conclusion</h3>\n<p>Absolute imports might befuddle a new developer for a while. If they understand it, then it is pretty easy to use. Therefore, I suggest including a few lines about importing mechanisms in your Readme, or you might link to this article. I am not going to change any content after I publish this article. I hope you enjoyed this small trick to better organize your React project.</p>\n<p>Have fun coding! 😃</p>\n<p><em>More content at </em><a href=\"http://plainenglish.io/\"><strong><em>plainenglish.io</em></strong></a></p>\n<img src=\"https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5b52f24d53c\" width=\"1\" height=\"1\" alt=\"\"><hr>\n<p><a href=\"https://javascript.plainenglish.io/why-and-how-to-use-absolute-imports-in-react-d5b52f24d53c\">Why and How to Use Absolute Imports in React</a> was originally published in <a href=\"https://javascript.plainenglish.io/\">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>\n",
"content": "\n<h4>Front End</h4>\n<h4>An easy way to maintain clean code in React</h4>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*jgQN6rI0OJB_OXgVTgOwLw.jpeg\"><figcaption>Photo by <a href=\"https://www.pexels.com/@ketut-subiyanto?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels\">Ketut Subiyanto</a> from <a href=\"https://www.pexels.com/photo/crop-faceless-man-packing-box-with-scotch-tape-4246109/?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels\">Pexels</a></figcaption></figure><p>Using absolute imports to better organize your React project is a great way. Relative imports are hard to follow and break during refactoring. Absolute imports manage your project easier as it grows. Forget long relative imports after this article. This is my 40th Medium article.</p>\n<h3>The Problem</h3>\n<p>What if your project’s folder structure is complex, and you need to <strong>go up</strong> in it? Inside of your components, you have imports that look like the below example with relative imports.</p>\n<pre>import {MyComponent} from ‘../../../../components/MyComponent’;</pre>\n<p>You can break the above import by changing the path of the component from which you are importing your MyComponent. Let’s assume you decide to move MyComponent into its own folder. Then you would need to update all of your imports in your project and add one extra ../ to all of your imports. Relative imports has some more problems.</p>\n<ul>\n<li>Pretty hard to refactor</li>\n<li>It becomes worse as you get further deeper into it.</li>\n<li>You need to change the entire codebase if you need to extract the code to be used externally as an NPM module.</li>\n</ul>\n<h3>Absolute Imports</h3>\n<p>By using absolute imports, you can alias some folders to a name like below:</p>\n<pre>import {MyComponent} from ‘components/MyComponent’;</pre>\n<p>Absolute imports have some advantages.</p>\n<ul>\n<li>There is no ../../../../hell. Therefore easier to type out the imports.</li>\n<li>Easily copy-paste the code with imports into another file in the project and not have to tinker with import paths.</li>\n<li>It is short and sweet</li>\n</ul>\n<p>The below example is a file with Relative imports.</p>\n<a href=\"https://medium.com/media/bf07582509895a0421291b5c22db5b93/href\">https://medium.com/media/bf07582509895a0421291b5c22db5b93/href</a><p>Make the imports in the above file prettier.</p>\n<a href=\"https://medium.com/media/f50a23cf68a84b3a75257aca796260ae/href\">https://medium.com/media/f50a23cf68a84b3a75257aca796260ae/href</a><p>Therefore, how can you use absolute imports with ReactJs?</p>\n<h4>Using TypeScript</h4>\n<p>If you need to set up absolute imports in your Typescript application add/update your tsconfig.json file in the root directory of the project. Then you need to update the compiler option baseUrl in the file.</p>\n<a href=\"https://medium.com/media/94d143b8d97ef92279a8442c500e4c56/href\">https://medium.com/media/94d143b8d97ef92279a8442c500e4c56/href</a><h4>Using JavaScript</h4>\n<p>Setting up absolute imports to Typescript and setting up absolute imports to JavaScript is pretty much the same process. Create the jsconfig.json file in the root directory of the project. Then you need to update the following snippet.</p>\n<a href=\"https://medium.com/media/b900ae2e75d9c9321443dfe726867272/href\">https://medium.com/media/b900ae2e75d9c9321443dfe726867272/href</a><p>Now you can import your components like this.</p>\n<pre>import {MyComponent} from ‘components/MyComponent’;</pre>\n<p>You can also use the compiler option paths as well. Perhaps you want to alias your component folder. For that, you need to set up your tsconfig.json, or jsconfig.json as shown in below:</p>\n<pre>{<br> \"compilerOptions\": {<br> \"baseUrl\": \"./\",<br> \"paths\": {<br> \"@component/*\": [\"src/components/*\"],<br> }<br> }<br>}</pre>\n<p>Now you can import the components from your component folder like this:</p>\n<pre>import {MyComponent} from ‘@component/MyComponent’;</pre>\n<p>is that enough?</p>\n<p>Well, no… You need to make your IDE smart to understand absolute imports in your files. Here I am going to mention the progress for the top 2 IDEs. Those are VS Code and WebStrom.</p>\n<h4>For VS Code</h4>\n<p>VS Code is smart enough to understand the tsconfig.json, or jsconfig.json file. Intellisense and jump-to-source are just working fine with absolute imports.</p>\n<p>Therefore, you can follow the above process.</p>\n<h4>For WebStrom / IntelliJ Idea</h4>\n<p>Select the src folder in the project window and right-click on it. Select the option <strong>Mark Directory as</strong> and then select the <strong>Resources Root</strong> option.</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/744/1*1QCjtXr7W8tAS97Etkna_w.png\"></figure><p>Now go to <strong>Settings</strong> -> <strong>Editor -</strong>> <strong>Code Style</strong> -> <strong>JavaScript </strong>and<strong> </strong>select the <strong>Imports</strong> tab. Then check the <strong>Use paths relative to the project, resource or sources roots</strong>.</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*VhExpM1Kx5SaHMvuIyAeHg.png\"></figure><p>Now WebStrom knows where the absolute imports are pointing. There won’t no warnings and autocomplete/ jump-to-source will work. This means the auto-import mechanism uses absolute imports.</p>\n<p>If you are a strict developer like me, use something like Airbnb’s ESLint config.</p>\n<h4>With ESLint</h4>\n<p>Create React App also has an ESLint setup but it has a minimal set of rules. <a href=\"https://github.com/benmosher/eslint-plugin-import\">eslint-plugin-import</a> is used by Airbnb and this plugin checks undefined imports. When you are going to use Airbnb’s ESLint config it will give you the error shown below:</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/592/1*7w-nu2REGmEs3V4-1dNcXw.png\"></figure><p>You can fix the error by add settings prop in your ESLint config. That setting prop point that your imports might be relative to src folder. Therefore, you need to add update your ESLint config in .eslintrc file like this:</p>\n<a href=\"https://medium.com/media/d608ef6ca698cb7586d1e89fb901eecf/href\">https://medium.com/media/d608ef6ca698cb7586d1e89fb901eecf/href</a><p>You don’t need to install any NPM modules to avoid the ESLint error, add the settings prop is enough.</p>\n<h4>By Convention</h4>\n<p>Absolute imports have been possible for a long time with Webpack. When you are naming your aliased folder, you need to use PascalCase/CamelCase because it is the convention follow in the <a href=\"https://webpack.js.org/configuration/resolve/#resolvealias\">Webpack</a>.</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/700/1*SsTWqQeNRLM8ReY5PBPK8w.png\"></figure><h3>Conclusion</h3>\n<p>Absolute imports might befuddle a new developer for a while. If they understand it, then it is pretty easy to use. Therefore, I suggest including a few lines about importing mechanisms in your Readme, or you might link to this article. I am not going to change any content after I publish this article. I hope you enjoyed this small trick to better organize your React project.</p>\n<p>Have fun coding! 😃</p>\n<p><em>More content at </em><a href=\"http://plainenglish.io/\"><strong><em>plainenglish.io</em></strong></a></p>\n<img src=\"https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5b52f24d53c\" width=\"1\" height=\"1\" alt=\"\"><hr>\n<p><a href=\"https://javascript.plainenglish.io/why-and-how-to-use-absolute-imports-in-react-d5b52f24d53c\">Why and How to Use Absolute Imports in React</a> was originally published in <a href=\"https://javascript.plainenglish.io/\">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>\n",
"enclosure": {},
"categories": [
"javascript",
"react",
"web-development",
"front-end-development",
"programming"
],
"clapCount": 98,
"voterCount": 12,
"responseCount": 0,
"readingTime": 4
},
{
"title": "How to mock network request in Jest",
"pubDate": "2021-10-03 20:32:09",
"link": "https://medium.com/geekculture/how-to-mock-network-request-in-jest-40958bb8d8e2?source=rss-b255948cc1f5------2",
"guid": "https://medium.com/p/40958bb8d8e2",
"author": "Sabesan Sathananthan",
"thumbnail": "https://cdn-images-1.medium.com/max/1024/1*poXRRZdZAElrrP9C3ZQLoQ.jpeg",
"description": "\n<h4>TESTING</h4>\n<h4>Mocking network requests even easier</h4>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*poXRRZdZAElrrP9C3ZQLoQ.jpeg\"><figcaption>Photo by <a href=\"https://unsplash.com/@tvick?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Taylor Vick</a> on <a href=\"https://unsplash.com/@tvick?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Unsplash</a></figcaption></figure><p>Nowadays, it is necessary to modify an older library to TS and perform unit testing. If the library is modified to TS, there is still a little bit better. Unit testing is purely a current study and sold now. For beginners to learn the Jest framework, I think the more troublesome thing in unit testing is to test network requests. So record some of the ways that Mock dropped Axios to initiate network requests. This is my 39th Medium article.</p>\n<h3>Introduction</h3>\n<p>The examples mentioned in the article are all in the <a href=\"https://github.com/sabesansathananthan/jest-mock-server\">jest-mock-server</a> repository. You can start the example directly by installing the package manager, for example, installing through yarn:</p>\n<pre>$ yarn install</pre>\n<p>Some commands are specified in the package.json, which are as follows:</p>\n<ul>\n<li>npm run build : The packaging command of rollup .</li>\n<li>npm run test:demo1 : Simply mock the network request library encapsulated.</li>\n<li>npm run test:demo2 : Complete the mock by re-implement hook.</li>\n<li>npm run test:demo3 : Use the library in Jest to complete the implementation of demo2.</li>\n<li>npm run test:demo4-5 : Start a node server, proxy the network request through the proxy of axios, and forward it to the started node server. By setting the corresponding unit test request and response data, the corresponding relationship is used to realize the test, which is jest-mock-server finished work.</li>\n</ul>\n<p>Here we encapsulate a layer of axios, which is closer to the real scene. You can view the test/demo/wrap-request.ts file. In fact, it simply creates an axios instance internally and forwards the response data.</p>\n<a href=\"https://medium.com/media/189a99f308e1f40a89b298507ec69d60/href\">https://medium.com/media/189a99f308e1f40a89b298507ec69d60/href</a><p>The test/demo/index.ts file simply exports a counter method, where these two parameters are processed to a certain extent before the network request is initiated. Then the response data is also processed to a certain extent, just to simulate related operations.</p>\n<a href=\"https://medium.com/media/2c1f8febcb377b42bd7bab7d64ed57e8/href\">https://medium.com/media/2c1f8febcb377b42bd7bab7d64ed57e8/href</a><p>Here Jest uses the browser environment simulated by JSDOM, the startup file test/config/setup.js is configured in the setupFiles attribute configured in jest.config.js, and JSDOM is initialized here.</p>\n<a href=\"https://medium.com/media/62edd6ebce331fbd8fbd0c1f8bba461e/href\">https://medium.com/media/62edd6ebce331fbd8fbd0c1f8bba461e/href</a><h3>demo1: Simple Mock network request</h3>\n<p>Simple mock processing is performed in test/demo1.test.js, and you can try to run it through npm run test:demo1. In fact, a mock operation is performed on the wrap-request library that wraps axios. wrap-request will be compiled when Jest is started. After the library is mocked here, all the files imported into the library afterward will get the mocked objects. In other words, we can think that this library has been rewritten, and the methods after rewriting are all JEST’s Mock Functions . You can use functions such as mockReturnValue for data simulation. For Mock Functions, please refer to this <a href=\"https://www.jestjs.cn/docs/mock-functions\">link</a>.</p>\n<a href=\"https://medium.com/media/5cad0c513dca3ae373ff71e603280117/href\">https://medium.com/media/5cad0c513dca3ae373ff71e603280117/href</a><p>Here we have completed the Mock of the return value, which means that we can control the value returned by the request in the wrap-request library. However, it was mentioned before that there are also certain processes for the incoming parameters. We haven’t made any assertions on this part of the content, so we also need to try to deal with this.</p>\n<h3>demo2: hook network request</h3>\n<p>demo2 can be tried to run through npm run test:demo2. As mentioned above, we can handle the return value but there is no way to assert whether the input parameters are processed correctly so we need to deal with this situation. Fortunately, Jest provides a way to directly implement the function library that is mocked. Therefore, Jest also provides a mockImplementation method, which is used in demo3. Here we have rewritten the mocked function library. We can also use jest.fn to complete Implementations . Here we write a hook function before returning and then implement assertions or specify return values in each test. In this way, the above problem can be solved, which is actually the realization of mockImplementation of Mock Functionsin Jest.</p>\n<a href=\"https://medium.com/media/55e00636b422895a42181b3e57fc4f48/href\">https://medium.com/media/55e00636b422895a42181b3e57fc4f48/href</a><h3>demo3: Use Jest’s mockImplementation</h3>\n<p>demo3 can be tried to run through npm run test:demo3. The example in demo2 is actually complicated to write. In Jest, Mock Functionshas the implementation of mockImplementation which can be used directly.</p>\n<a href=\"https://medium.com/media/ca006cc73a21e00c49fa70a4026c7764/href\">https://medium.com/media/ca006cc73a21e00c49fa70a4026c7764/href</a><h3>demo4–5: Really initiate a network request</h3>\n<p>demo4 and demo5 can be tried to run through npm run test:demo4–5. In this way, a real data request is made. Here, axios proxy will be used to forward internal data requests to the specified server port. Therefore, the server is also started locally and the test is performed by specifying the request and response data related to the corresponding path. If the requested data is incorrect then the related response data will not be matched normally. Therefore, the request will directly return 500. If the returned response data is incorrect, it will also be captured during the assertion. In the jest-mock-server library, first, we need to specify three files which are corresponding to the three life cycles that each unit test file to be executed before startup. Jest test is executed before the three life cycles and the three life cycles are executed after the Jest test is completed. The three files which we need to specify are the setupFiles, globalSetup, and globalTeardown configuration items of the jest.config.js configuration file.</p>\n<p>First we are going to start with setupFiles. In addition to initializing JSDOM, we also need to operate the default proxy of axios. Because the solution adopted is to use the proxy of axios to forward data requests. Therefore, it is necessary to set the proxy value at the forefront of the unit test.</p>\n<a href=\"https://medium.com/media/9b4cb805078f7a02e4b544bd746591e2/href\">https://medium.com/media/9b4cb805078f7a02e4b544bd746591e2/href</a><p>Once we set up the above file inside thetest/config folder then we need to add two more files in there which are globalSetup and globalTeardown . These two files refer to the operations performed before the Jest unit test starts and after all tests are completed. We put the server startup and shutdown operations in those two files.</p>\n<blockquote>Please note that the file running in these two files is a separate independent <em>contex</em> which has nothing to do with the <em>contex</em> of any unit test including the file specified by the setupFiles configuration item. Therefore, all the data here is either specified in the configuration file, or It is to transmit between server ports through the network.</blockquote>\n<a href=\"https://medium.com/media/3b08699d87ba11d0f53387fc5861f153/href\">https://medium.com/media/3b08699d87ba11d0f53387fc5861f153/href</a><p>For the configuration port and domain name information, put it directly in the globals field in jest.config.js. For the debug configuration item, it is recommended to use it in conjunction with test.only.</p>\n<a href=\"https://medium.com/media/9257d7afd40ae230f49809ec06859a58/href\">https://medium.com/media/9257d7afd40ae230f49809ec06859a58/href</a><p>Now, there may be suggestion that why the server should not be started and shut down in the beforeAll and afterAll life cycles of each unit test file. Therefore, I have tried this solution. In this solution, for each test file, the server is started and then shut down. Therefore, this solution is relatively time-consuming. But in theory, this solution is reasonable. After all, it is true that data isolation is necessary. But there is a problem when afterAll is closed. It does not actually close the server and port occupation because the close method is called when the node server is closed. WhenafterAll is closed, It just stopped processing the request but the port is still occupied. When the second unit test file is started, an exception will be thrown that the port is being used. Although I tried some solutions, they are not ideal because sometimes the port is still occupied. Especially when the node is run for the first time after it is turned on, the probability of abnormality is relatively high. Therefore, the effect is not very satisfactory. In the end, the complete isolation scheme is adopted. For specific related issues, please refer to this <a href=\"https://stackoverflow.com/questions/14626636/how-do-i-shutdown-a-node-js-https-server-immediately\">link</a>.</p>\n<p>Since we adopt a completely isolated solution, there are only two options when we want to transmit the request and response data for the test request. The two solutions are either when the server is started all the data is specified in the test/config/global-setup.js file or the data is transmitted through the network when the server is running, the path is specified and the network request of the path will carry data and the data request will be specified in the closure of the server. Therefore, both options are supported here. I think it is more appropriate to specify your own data in each unit test file, so here is only one example of specifying the data to be tested in the unit test file. Regarding the data to be tested, a DataMapper type is specified to reduce exceptions caused by type errors. Therefore, two data sets are exemplified here. In addition, regular expressions are supported when matching query and data. The structure of the DataMapper type is relatively standard.</p>\n<a href=\"https://medium.com/media/49d069f721d4cff024b11b03333415db/href\">https://medium.com/media/49d069f721d4cff024b11b03333415db/href</a><p>In the below two unit tests, the data to be tested is specified in beforeAll. Note that beforeAll is return setSuitesData(data) because the unit test is executed after the data is set and the response is successful, followed by the normal request and response whether the assertion test is correct.</p>\n<a href=\"https://medium.com/media/ea84a68a6c5934e5c6806b48a265edf8/href\">https://medium.com/media/ea84a68a6c5934e5c6806b48a265edf8/href</a><img src=\"https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40958bb8d8e2\" width=\"1\" height=\"1\" alt=\"\"><hr>\n<p><a href=\"https://medium.com/geekculture/how-to-mock-network-request-in-jest-40958bb8d8e2\">How to mock network request in Jest</a> was originally published in <a href=\"https://medium.com/geekculture\">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>\n",
"content": "\n<h4>TESTING</h4>\n<h4>Mocking network requests even easier</h4>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*poXRRZdZAElrrP9C3ZQLoQ.jpeg\"><figcaption>Photo by <a href=\"https://unsplash.com/@tvick?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Taylor Vick</a> on <a href=\"https://unsplash.com/@tvick?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Unsplash</a></figcaption></figure><p>Nowadays, it is necessary to modify an older library to TS and perform unit testing. If the library is modified to TS, there is still a little bit better. Unit testing is purely a current study and sold now. For beginners to learn the Jest framework, I think the more troublesome thing in unit testing is to test network requests. So record some of the ways that Mock dropped Axios to initiate network requests. This is my 39th Medium article.</p>\n<h3>Introduction</h3>\n<p>The examples mentioned in the article are all in the <a href=\"https://github.com/sabesansathananthan/jest-mock-server\">jest-mock-server</a> repository. You can start the example directly by installing the package manager, for example, installing through yarn:</p>\n<pre>$ yarn install</pre>\n<p>Some commands are specified in the package.json, which are as follows:</p>\n<ul>\n<li>npm run build : The packaging command of rollup .</li>\n<li>npm run test:demo1 : Simply mock the network request library encapsulated.</li>\n<li>npm run test:demo2 : Complete the mock by re-implement hook.</li>\n<li>npm run test:demo3 : Use the library in Jest to complete the implementation of demo2.</li>\n<li>npm run test:demo4-5 : Start a node server, proxy the network request through the proxy of axios, and forward it to the started node server. By setting the corresponding unit test request and response data, the corresponding relationship is used to realize the test, which is jest-mock-server finished work.</li>\n</ul>\n<p>Here we encapsulate a layer of axios, which is closer to the real scene. You can view the test/demo/wrap-request.ts file. In fact, it simply creates an axios instance internally and forwards the response data.</p>\n<a href=\"https://medium.com/media/189a99f308e1f40a89b298507ec69d60/href\">https://medium.com/media/189a99f308e1f40a89b298507ec69d60/href</a><p>The test/demo/index.ts file simply exports a counter method, where these two parameters are processed to a certain extent before the network request is initiated. Then the response data is also processed to a certain extent, just to simulate related operations.</p>\n<a href=\"https://medium.com/media/2c1f8febcb377b42bd7bab7d64ed57e8/href\">https://medium.com/media/2c1f8febcb377b42bd7bab7d64ed57e8/href</a><p>Here Jest uses the browser environment simulated by JSDOM, the startup file test/config/setup.js is configured in the setupFiles attribute configured in jest.config.js, and JSDOM is initialized here.</p>\n<a href=\"https://medium.com/media/62edd6ebce331fbd8fbd0c1f8bba461e/href\">https://medium.com/media/62edd6ebce331fbd8fbd0c1f8bba461e/href</a><h3>demo1: Simple Mock network request</h3>\n<p>Simple mock processing is performed in test/demo1.test.js, and you can try to run it through npm run test:demo1. In fact, a mock operation is performed on the wrap-request library that wraps axios. wrap-request will be compiled when Jest is started. After the library is mocked here, all the files imported into the library afterward will get the mocked objects. In other words, we can think that this library has been rewritten, and the methods after rewriting are all JEST’s Mock Functions . You can use functions such as mockReturnValue for data simulation. For Mock Functions, please refer to this <a href=\"https://www.jestjs.cn/docs/mock-functions\">link</a>.</p>\n<a href=\"https://medium.com/media/5cad0c513dca3ae373ff71e603280117/href\">https://medium.com/media/5cad0c513dca3ae373ff71e603280117/href</a><p>Here we have completed the Mock of the return value, which means that we can control the value returned by the request in the wrap-request library. However, it was mentioned before that there are also certain processes for the incoming parameters. We haven’t made any assertions on this part of the content, so we also need to try to deal with this.</p>\n<h3>demo2: hook network request</h3>\n<p>demo2 can be tried to run through npm run test:demo2. As mentioned above, we can handle the return value but there is no way to assert whether the input parameters are processed correctly so we need to deal with this situation. Fortunately, Jest provides a way to directly implement the function library that is mocked. Therefore, Jest also provides a mockImplementation method, which is used in demo3. Here we have rewritten the mocked function library. We can also use jest.fn to complete Implementations . Here we write a hook function before returning and then implement assertions or specify return values in each test. In this way, the above problem can be solved, which is actually the realization of mockImplementation of Mock Functionsin Jest.</p>\n<a href=\"https://medium.com/media/55e00636b422895a42181b3e57fc4f48/href\">https://medium.com/media/55e00636b422895a42181b3e57fc4f48/href</a><h3>demo3: Use Jest’s mockImplementation</h3>\n<p>demo3 can be tried to run through npm run test:demo3. The example in demo2 is actually complicated to write. In Jest, Mock Functionshas the implementation of mockImplementation which can be used directly.</p>\n<a href=\"https://medium.com/media/ca006cc73a21e00c49fa70a4026c7764/href\">https://medium.com/media/ca006cc73a21e00c49fa70a4026c7764/href</a><h3>demo4–5: Really initiate a network request</h3>\n<p>demo4 and demo5 can be tried to run through npm run test:demo4–5. In this way, a real data request is made. Here, axios proxy will be used to forward internal data requests to the specified server port. Therefore, the server is also started locally and the test is performed by specifying the request and response data related to the corresponding path. If the requested data is incorrect then the related response data will not be matched normally. Therefore, the request will directly return 500. If the returned response data is incorrect, it will also be captured during the assertion. In the jest-mock-server library, first, we need to specify three files which are corresponding to the three life cycles that each unit test file to be executed before startup. Jest test is executed before the three life cycles and the three life cycles are executed after the Jest test is completed. The three files which we need to specify are the setupFiles, globalSetup, and globalTeardown configuration items of the jest.config.js configuration file.</p>\n<p>First we are going to start with setupFiles. In addition to initializing JSDOM, we also need to operate the default proxy of axios. Because the solution adopted is to use the proxy of axios to forward data requests. Therefore, it is necessary to set the proxy value at the forefront of the unit test.</p>\n<a href=\"https://medium.com/media/9b4cb805078f7a02e4b544bd746591e2/href\">https://medium.com/media/9b4cb805078f7a02e4b544bd746591e2/href</a><p>Once we set up the above file inside thetest/config folder then we need to add two more files in there which are globalSetup and globalTeardown . These two files refer to the operations performed before the Jest unit test starts and after all tests are completed. We put the server startup and shutdown operations in those two files.</p>\n<blockquote>Please note that the file running in these two files is a separate independent <em>contex</em> which has nothing to do with the <em>contex</em> of any unit test including the file specified by the setupFiles configuration item. Therefore, all the data here is either specified in the configuration file, or It is to transmit between server ports through the network.</blockquote>\n<a href=\"https://medium.com/media/3b08699d87ba11d0f53387fc5861f153/href\">https://medium.com/media/3b08699d87ba11d0f53387fc5861f153/href</a><p>For the configuration port and domain name information, put it directly in the globals field in jest.config.js. For the debug configuration item, it is recommended to use it in conjunction with test.only.</p>\n<a href=\"https://medium.com/media/9257d7afd40ae230f49809ec06859a58/href\">https://medium.com/media/9257d7afd40ae230f49809ec06859a58/href</a><p>Now, there may be suggestion that why the server should not be started and shut down in the beforeAll and afterAll life cycles of each unit test file. Therefore, I have tried this solution. In this solution, for each test file, the server is started and then shut down. Therefore, this solution is relatively time-consuming. But in theory, this solution is reasonable. After all, it is true that data isolation is necessary. But there is a problem when afterAll is closed. It does not actually close the server and port occupation because the close method is called when the node server is closed. WhenafterAll is closed, It just stopped processing the request but the port is still occupied. When the second unit test file is started, an exception will be thrown that the port is being used. Although I tried some solutions, they are not ideal because sometimes the port is still occupied. Especially when the node is run for the first time after it is turned on, the probability of abnormality is relatively high. Therefore, the effect is not very satisfactory. In the end, the complete isolation scheme is adopted. For specific related issues, please refer to this <a href=\"https://stackoverflow.com/questions/14626636/how-do-i-shutdown-a-node-js-https-server-immediately\">link</a>.</p>\n<p>Since we adopt a completely isolated solution, there are only two options when we want to transmit the request and response data for the test request. The two solutions are either when the server is started all the data is specified in the test/config/global-setup.js file or the data is transmitted through the network when the server is running, the path is specified and the network request of the path will carry data and the data request will be specified in the closure of the server. Therefore, both options are supported here. I think it is more appropriate to specify your own data in each unit test file, so here is only one example of specifying the data to be tested in the unit test file. Regarding the data to be tested, a DataMapper type is specified to reduce exceptions caused by type errors. Therefore, two data sets are exemplified here. In addition, regular expressions are supported when matching query and data. The structure of the DataMapper type is relatively standard.</p>\n<a href=\"https://medium.com/media/49d069f721d4cff024b11b03333415db/href\">https://medium.com/media/49d069f721d4cff024b11b03333415db/href</a><p>In the below two unit tests, the data to be tested is specified in beforeAll. Note that beforeAll is return setSuitesData(data) because the unit test is executed after the data is set and the response is successful, followed by the normal request and response whether the assertion test is correct.</p>\n<a href=\"https://medium.com/media/ea84a68a6c5934e5c6806b48a265edf8/href\">https://medium.com/media/ea84a68a6c5934e5c6806b48a265edf8/href</a><img src=\"https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40958bb8d8e2\" width=\"1\" height=\"1\" alt=\"\"><hr>\n<p><a href=\"https://medium.com/geekculture/how-to-mock-network-request-in-jest-40958bb8d8e2\">How to mock network request in Jest</a> was originally published in <a href=\"https://medium.com/geekculture\">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>\n",
"enclosure": {},
"categories": [
"javascript",
"jest",
"unit-testing",
"web-development",
"testing"
],
"clapCount": 148,
"voterCount": 12,
"responseCount": 0,
"readingTime": 6
},
{
"title": "How To Reuse React Components",
"pubDate": "2021-06-24 15:25:34",
"link": "https://medium.com/codezillas/how-to-reuse-react-components-851ffcc68a9c?source=rss-b255948cc1f5------2",
"guid": "https://medium.com/p/851ffcc68a9c",
"author": "Sabesan Sathananthan",
"thumbnail": "https://cdn-images-1.medium.com/max/1024/1*HvyPiGMOis-_Gxp6cyttiA.jpeg",
"description": "\n<h4>Mixins, HOC, render props, and Hooks are four ways to reuse components</h4>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*HvyPiGMOis-_Gxp6cyttiA.jpeg\"><figcaption>Photo by <a href=\"https://www.pexels.com/@vlada-karpovich?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels\">Vlada Karpovich</a> from <a href=\"https://www.pexels.com/photo/photo-of-pen-beside-ink-4668356/?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels\">Pexels</a></figcaption></figure><p>Now frontend engineering is more and more important. Although Ctrl+C and Ctrl+V can also be used to complete requirements, once they are modified, it becomes a huge task. Therefore, copying of code is reduced, and the packaging and reuse capabilities are increased to achieve maintainability and reversibility. The code used becomes particularly important.</p>\n<p>In React, components are the main unit of code reuse. The combination-based component reuse mechanism is quite elegant, but for more fine-grained logic (state logic, behavior logic, etc.), reuse is not so easy. It is difficult to disassemble the state logic as a reusable function or component. In fact, before the appearance of Hooks, there was a lack of a simple and direct way of component behavior extension, which is considered to be mixins, higher-order components (HOC), and render props. The upper-level model explored under the existing (component mechanism) game rules has not solved the problem of logic reuse between components from the root. This is my 38th Medium article.</p>\n<h3>Mixins</h3>\n<p>Of course, React no longer recommends using mixins as a reuse solution for a long time, but it can still provide support for mixins through create-react-class. Note that mixins are not supported when declaring components in ES6 classes.</p>\n<p>Mixins allow multiple React components to share code. They are very similar to mixins in Python or traits in PHP. The emergence of the mixin solution comes from an OOP intuition. In the early days, it only provided React.createClass() API to define components. (In React v15.5.0, it is officially abandoned and moved to create-react-class). Naturally, (class) inheritance has become an intuitive attempt, and in JavaScript prototype-based extension mode, it is similar to the inherited mixin scheme. It has become a good solution. Mixin is mainly used to solve the reuse problem of life cycle logic and state logic, and allows the component life cycle to be extended from the outside. This is especially important in Flux and other modes, but many defects have also appeared in continuous practice:</p>\n<ul>\n<li>There is an implicit dependency between the component and the mixin (Mixin often depends on the specific method of the component, but the dependency is not known when the component is defined).</li>\n<li>There may be conflicts between multiple mixin (such as defining the same state field).</li>\n<li>Mixin tends to add more states, which reduces the predictability of the application and leads to a sharp increase in complexity.</li>\n<li>Implicit dependencies lead to opaque dependencies, and maintenance costs and understanding costs are rising rapidly.</li>\n<li>It is difficult to quickly understand the behavior of components, and it is necessary to fully understand all the extension behaviors that rely on mixin and their mutual influence.</li>\n<li>The method and state field of the component itself is afraid to be easily deleted because it is difficult to determine whether mixin depends on it.</li>\n<li>Mixin is also difficult to maintain, because Mixin logic will eventually be flattened and merged together, and it is difficult to figure out the input and output of a Mixin.</li>\n</ul>\n<p>There is no doubt that these problems are fatal, so Reactv0.13.0 abandoned Mixin static crosscutting (similar to inherited reuse) and moved to HOC higher-order components (similar to combined reuse).</p>\n<h4>Example</h4>\n<p>The example of the ancient version, a common scenario is: A component needs to be updated regularly. It is easy to do it with setInterval(), but it is very important to cancel the timer when it is not needed to save memory. React provides a lifecycle method to inform the component. The time of creation or destruction, the following Mixin, use setInterval() and ensure that the timer is cleaned up when the component is destroyed.</p>\n<a href=\"https://medium.com/media/6fd5344ded564231f982182c4310121b/href\">https://medium.com/media/6fd5344ded564231f982182c4310121b/href</a><h3>HOC</h3>\n<p>After Mixin, HOC high-order components take on the heavy responsibility and become the recommended solution for logical reuse between components. High-order components reveal a high-order atmosphere from their names. In fact, this concept should be derived from high-order functions of JavaScript. The high-order function is a function that accepts a function as input or output. It can be thought that currying is a higher-order function. The definition of higher-order components is also given in the React document. Higher-order components receive components and return new components. function. The specific meaning is: High-order components can be seen as an implementation of React decoration pattern. High-order components are a function, and the function accepts a component as a parameter and returns a new component. It will return an enhanced React components. High-order components can make our code more reusable, logical and abstract, can hijack the render method, and can also control propsand state.</p>\n<p>Comparing Mixin and HOC, Mixin is a mixed-in mode. In actual use, Mixin is still very powerful, allowing us to share the same method in multiple components, but it will also continue to add new methods and attributes to the components. The component itself can not only perceive but also need to do related processing (such as naming conflicts, state maintenance, etc.). Once the mixed modules increase, the entire component becomes difficult to maintain. Mixin may introduce invisible attributes, such as in the Mixin method used in the rendering component brings invisible property props and states to the component. Mixin may depend on each other and is coupled with each other, which is not conducive to code maintenance. In addition, the methods in different Mixin may conflict with each other. Previously React officially recommended using Mixin to solve problems related to cross-cutting concerns, but because using Mixin may cause more trouble, the official recommendation is now to use HOC. High-order component HOC belong to the idea of functional programming. The wrapped components will not be aware of the existence of high-order components, and the components returned by high-order components will have a functional enhancement effect on the original components. Based on this, React officially recommends the use of high-order components.</p>\n<p>Although HOC does not have so many fatal problems, it also has some minor flaws:</p>\n<ul>\n<li>Scalability restriction: HOC cannot completely replace Mixin. In some scenarios, Mixin can but HOC cannot. For example, PureRenderMixin, because HOC cannot access the State of subcomponents from the outside, and at the same time filter out unnecessary updates through shouldComponentUpdate. Therefore, React After supporting ES6Class, React.PureComponent is provided to solve this problem.</li>\n<li>Ref transfer problem: Ref is cut off. The transfer problem of Ref is quite annoying under the layers of packaging. The function Ref can alleviate part of it (allowing HOC to learn about node creation and destruction), so the React.forwardRef API API was introduced later.</li>\n<li>WrapperHell: HOC is flooded, and WrapperHell appears (there is no problem that cannot be solved by one layer, if there is, then two layers). Multi-layer abstraction also increases complexity and cost of understanding. This is the most critical defect. In HOC mode There is no good solution.</li>\n</ul>\n<h4>Example</h4>\n<p>Specifically, a high-order component is a function whose parameter is a component and the return value is a new component. A component converts props into a UI but a high-order component converts a component into another component. HOC is very common in React third-party libraries, such as Redux’s connect and Relay’s createFragmentContainer.</p>\n<a href=\"https://medium.com/media/90068090af75d82f09618a2e3b129735/href\">https://medium.com/media/90068090af75d82f09618a2e3b129735/href</a><p>Attention should be paid here, do not try to modify the component prototype in the HOC in any way, but should use the combination method to realize the function by packaging the component in the container component. Under normal circumstances, there are two ways to implement high-order components:</p>\n<ul>\n<li>Property agent Props Proxy.</li>\n<li>Reverse inheritance Inheritance Inversion.</li>\n</ul>\n<h4>Property Agent</h4>\n<p>For example, we can add a stored id attribute value to the incoming component. We can add a props to this component through high-order components. Of course, we can also operate on the props in the WrappedComponent component in JSX. Note that it is not to manipulate the incoming WrappedComponent class, we should not directly modify the incoming component, but can operate on it in the process of combination.</p>\n<a href=\"https://medium.com/media/49e24540e51916b4fb3de4aaabb24ed1/href\">https://medium.com/media/49e24540e51916b4fb3de4aaabb24ed1/href</a><p>We can also use high-order components to load the state of new components into the packaged components. For example, we can use high-order components to convert uncontrolled components into controlled components.</p>\n<a href=\"https://medium.com/media/c21c2997d27e3522421b423881bfa3a3/href\">https://medium.com/media/c21c2997d27e3522421b423881bfa3a3/href</a><p>Or our purpose is to wrap it with other components to achieve the purpose of layout or style.</p>\n<a href=\"https://medium.com/media/a67368bf8f443f35fa16cb084dd3581b/href\">https://medium.com/media/a67368bf8f443f35fa16cb084dd3581b/href</a><h4>Reverse inheritance</h4>\n<p>Reverse inheritance means that the returned component inherits the previous component. In reverse inheritance, we can do a lot of operations, modify state, props and even flip the Element Tree. There is an important point in the reverse inheritance that reverse inheritance cannot ensure that the complete sub-component tree is parsed. That means if the parsed element tree contains components (function type or Class type), the sub-components of the component can no longer be manipulated.</p>\n<p>When we use reverse inheritance to implement high-order components, we can control rendering through rendering hijacking. Specifically, we can consciously control the rendering process of WrappedComponent to control the results of rendering control. For example, we can decide whether to render components according to some parameters.</p>\n<a href=\"https://medium.com/media/2f51f1a2e79f2d530f865980dba2158b/href\">https://medium.com/media/2f51f1a2e79f2d530f865980dba2158b/href</a><p>We can even hijack the life cycle of the original component by rewriting.</p>\n<a href=\"https://medium.com/media/d0d1d1a2e3655228e9e6214117d3fa91/href\">https://medium.com/media/d0d1d1a2e3655228e9e6214117d3fa91/href</a><p>Since it is actually an inheritance relationship, we can read the props and state of the component. If necessary, we can even add, modify, and delete the props and state. Of course, the premise is that the risks caused by the modification need to be controlled by yourself. In some cases, we may need to pass in some parameters for the high-order attributes, then we can pass in the parameters in the form of currying, and cooperate with the high-order components to complete the operation similar to the closure of the component.</p>\n<a href=\"https://medium.com/media/c93764203e66ee528fa2590b469fe091/href\">https://medium.com/media/c93764203e66ee528fa2590b469fe091/href</a><h4>note</h4>\n<p><strong>Don’t change the original components</strong></p>\n<p>Don’t try to modify the component prototype in HOC, or change it in other ways.</p>\n<a href=\"https://medium.com/media/38ab4b11e2b2e2bd581eca1ce0cfc6e6/href\">https://medium.com/media/38ab4b11e2b2e2bd581eca1ce0cfc6e6/href</a><p>Doing so will have some undesirable consequences. One is that the input component can no longer be used as before the HOC enhancement. What is more serious is that if you use another HOC that also modifies componentDidUpdate to enhance it, the previous HOC will be invalid, and this HOC cannot be applied to functional components that have no life cycle.<br>Modifying the HOC of the incoming component is a bad abstraction, and the caller must know how they are implemented to avoid conflicts with other HOC. HOC should not modify the incoming components, but should use a combination of components to achieve functions by packaging the components in container components.</p>\n<a href=\"https://medium.com/media/9d539457779e7022762037d655c757e3/href\">https://medium.com/media/9d539457779e7022762037d655c757e3/href</a><p><strong>Filter props</strong></p>\n<p>HOC adds features to components and should not significantly change the convention itself. The components returned by HOC should maintain similar interfaces with the original components. HOC should transparently transmit props that have nothing to do with itself, and most HOC should include a render method similar to the following.</p>\n<a href=\"https://medium.com/media/674a9a7a926cee12af9dbd9e6423db36/href\">https://medium.com/media/674a9a7a926cee12af9dbd9e6423db36/href</a><p><strong>Maximum composability</strong></p>\n<p>Not all HOCs are the same. Sometimes it only accepts one parameter, which is the packaged component.</p>\n<pre>const NavbarWithRouter = withRouter(Navbar);</pre>\n<p>HOC can usually receive multiple parameters. For example, in Relay, HOC additionally receives a configuration object to specify the data dependency of the component.</p>\n<pre>const CommentWithRelay = Relay.createContainer(Comment, config);</pre>\n<p>The most common HOC signatures are as follows, connect is a higher-order function that returns higher-order components.</p>\n<a href=\"https://medium.com/media/590de18c82ad90e07cf1f8fed23a9845/href\">https://medium.com/media/590de18c82ad90e07cf1f8fed23a9845/href</a><p>This form may seem confusing or unnecessary, but it has a useful property, like the single-parameter HOC returned by the connect function has the signature Component => Component , and functions with the same output type and input type can be easily combined. The same attributes also allow connect and other HOCs to assume the role of decorator. In addition, many third-party libraries provide compose tool functions, including lodash, Redux, and Ramda.</p>\n<a href=\"https://medium.com/media/9cbc152eb50e35834c4d012ba48bfdbe/href\">https://medium.com/media/9cbc152eb50e35834c4d012ba48bfdbe/href</a><p><strong>Don’t use HOC in the render method</strong></p>\n<p>React ’s diff algorithm uses the component identifier to determine whether it should update the existing subtree or discard it and mount the new subtree. If the component returned from the render is the same as the component in the previous render ===, React passes The subtree is distinguished from the new subtree to recursively update the subtree, and if they are not equal, the previous subtree is completely unloaded.<br>Usually, you don’t need to consider this when using it, but it is very important for HOC, because it means that you should not apply HOC to a component in the render method of the component.</p>\n<a href=\"https://medium.com/media/01ec9da706301817b5d6ae40a4748a33/href\">https://medium.com/media/01ec9da706301817b5d6ae40a4748a33/href</a><p>This is not just a performance issue. Re-mounting the component will cause the state of the component and all its subcomponents to be lost. If the HOC is created outside the component, the component will only be created once. So every time you render it will be the same component. Generally speaking, this is consistent with your expected performance. In rare cases, you need to call HOC dynamically, you can call it in the component’s lifecycle method or its constructor.</p>\n<p><strong>Be sure to copy static methods</strong></p>\n<p>Sometimes it is useful to define static methods on React components. For example, the Relay container exposes a static method getFragment to facilitate the composition of GraphQL fragments. But when you apply HOC to a component, the original component will be packaged with a container component, which means that the new component does not have any static methods of the original component.</p>\n<a href=\"https://medium.com/media/efea68083923fe3dd728247948db447f/href\">https://medium.com/media/efea68083923fe3dd728247948db447f/href</a><p>To solve this problem, you can copy these methods to the container component before returning.</p>\n<a href=\"https://medium.com/media/9abac726b9373ce25fce08cf13c3fc22/href\">https://medium.com/media/9abac726b9373ce25fce08cf13c3fc22/href</a><p>But to do this, you need to know which methods should be copied. You can use hoist-non-react-statics to automatically copy all non-React static methods.</p>\n<a href=\"https://medium.com/media/791281382a5f23b7de315432be7c3aab/href\">https://medium.com/media/791281382a5f23b7de315432be7c3aab/href</a><p>In addition to exporting components, another feasible solution is to additionally export this static method.</p>\n<a href=\"https://medium.com/media/3d9ffdbc5203c4e03a2864d4b6ceadcb/href\">https://medium.com/media/3d9ffdbc5203c4e03a2864d4b6ceadcb/href</a><p><strong>Refs will not be passed</strong></p>\n<p>Although the convention of high-level components is to pass all props to the packaged component, this does not apply to refs, because ref is not actually a prop, just like a key, it is specifically handled by React. If the ref is added to the return component of the HOC, the ref reference points to the container component, not the packaged component. This problem can be explicitly forwarded to the internal component through the React.forwardRefAPI refs.</p>\n<a href=\"https://medium.com/media/b2badf123b0fde8ea364b52fc69fb78c/href\">https://medium.com/media/b2badf123b0fde8ea364b52fc69fb78c/href</a><h3>Render Props</h3>\n<p>Like HOC, Render props is also a veteran model that has always existed. render props refers to a simple technology that uses a props valued as a function to share code between a kind of React components. A component with render props receives a function. This function Return a React element and call it instead of implementing its own rendering logic. Render props is a function props used to tell the component what content needs to be rendered. It is also a way to implement component logic reuse. Simply put, it is being copied. In the component used, pass a prop property named render (the property name may not render, as long as the value is a function). The property is a function. This function accepts an object and returns a subcomponent, which will The object in the function parameter is passed as props to the newly generated component, and when using the caller component, you only need to decide where to renderthe component and what logic to renderand pass in the relevant object.<br>Comparing HOC and Render props, technically, both are based on the component combination mechanism. Render props has the same extensibility as HOC. It is called Render props. It does not mean that it can only be used to reuse rendering logic, but that it is here. In this mode, the components are combined through render(), similar to the establishment of a combination relationship through Wrapper’s render() in HOC mode. The two are very similar, and they will also produce a layer of Wrapper. In fact, Render props and HOC . It can even be converted to each other.<br>Similarly, Render props will have some problems:</p>\n<ul>\n<li>The data flow is more intuitive. The descendant components can clearly see the source of the data, but in essence, Render props is implemented based on closures. A large number of component reuse will inevitably introduce the callback hell problem.</li>\n<li>The context of the component is lost, so there is no this.propsproperty, and this.props.childern cannot be accessed like HOC.</li>\n</ul>\n<a href=\"https://medium.com/media/64a91bfecbecd6c5b4769f5780282dbb/href\">https://medium.com/media/64a91bfecbecd6c5b4769f5780282dbb/href</a><h3>Hooks</h3>\n<p>There are endless code reuse solutions, but overall code reuse is still very complicated. A large part of this is because fine-grained code reuse should not be bundled with component reuse. HOC, Render props, etc. are based on component combination The solution is equivalent to first packaging the logic to be reused into components, and then using the component reuse mechanism to achieve logic reuse. Naturally, it is limited to component reuse, so there are problems such as limited scalability, Ref partition, Wrapper Hell, etc. , Then we need to have a simple and direct way of code reuse. Functions. Separating reusable logic into functions should be the most direct and cost-effective way of code reuse. But for state logic, some abstract patterns are still needed. (Such as Observable) can be reused, which is exactly the idea of Hooks, using functions as the smallest code reuse unit, and built-in some modes to simplify the reuse of state logic. Compared with the other solutions mentioned above, Hooks makes the logic reuse within the component no longer bundled with the component reuse. It is really trying to solve the problem of fine-grained logic reuse (between components) from the lower level. In addition, this statement The modular logic reuse scheme further extends the explicit data flow and combination ideas between components to the components.<br>File Hooks are not perfect either, but for now, its disadvantages are as follows:</p>\n<ul>\n<li>The additional learning cost mainly lies in the comparison between Functional Component and Class Component .</li>\n<li>There are restrictions on the writing method (cannot appear in conditions, loops), and the writing restrictions increase the cost of reconstruction.</li>\n<li>It destroys the performance optimization effect of PureComponent and React.memo shallow comparison. In order to get the latest props and state, the event function must be recreated every render()</li>\n<li>In closure scenarios, old state and props values may be referenced.</li>\n<li>The internal implementation is not intuitive, relying on a mutable global state, and no longer so pure.</li>\n<li>React.memo can’t completely replace shouldComponentUpdate (because state change is not available, only for props change).</li>\n<li>The useStateAPI is not perfect in design.</li>\n</ul>\n<a href=\"https://medium.com/media/6b1308a30a4cc6f973b8276a25aec06d/href\">https://medium.com/media/6b1308a30a4cc6f973b8276a25aec06d/href</a><img src=\"https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=851ffcc68a9c\" width=\"1\" height=\"1\" alt=\"\"><hr>\n<p><a href=\"https://medium.com/codezillas/how-to-reuse-react-components-851ffcc68a9c\">How To Reuse React Components</a> was originally published in <a href=\"https://medium.com/codezillas\">Codezillas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>\n",
"content": "\n<h4>Mixins, HOC, render props, and Hooks are four ways to reuse components</h4>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*HvyPiGMOis-_Gxp6cyttiA.jpeg\"><figcaption>Photo by <a href=\"https://www.pexels.com/@vlada-karpovich?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels\">Vlada Karpovich</a> from <a href=\"https://www.pexels.com/photo/photo-of-pen-beside-ink-4668356/?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels\">Pexels</a></figcaption></figure><p>Now frontend engineering is more and more important. Although Ctrl+C and Ctrl+V can also be used to complete requirements, once they are modified, it becomes a huge task. Therefore, copying of code is reduced, and the packaging and reuse capabilities are increased to achieve maintainability and reversibility. The code used becomes particularly important.</p>\n<p>In React, components are the main unit of code reuse. The combination-based component reuse mechanism is quite elegant, but for more fine-grained logic (state logic, behavior logic, etc.), reuse is not so easy. It is difficult to disassemble the state logic as a reusable function or component. In fact, before the appearance of Hooks, there was a lack of a simple and direct way of component behavior extension, which is considered to be mixins, higher-order components (HOC), and render props. The upper-level model explored under the existing (component mechanism) game rules has not solved the problem of logic reuse between components from the root. This is my 38th Medium article.</p>\n<h3>Mixins</h3>\n<p>Of course, React no longer recommends using mixins as a reuse solution for a long time, but it can still provide support for mixins through create-react-class. Note that mixins are not supported when declaring components in ES6 classes.</p>\n<p>Mixins allow multiple React components to share code. They are very similar to mixins in Python or traits in PHP. The emergence of the mixin solution comes from an OOP intuition. In the early days, it only provided React.createClass() API to define components. (In React v15.5.0, it is officially abandoned and moved to create-react-class). Naturally, (class) inheritance has become an intuitive attempt, and in JavaScript prototype-based extension mode, it is similar to the inherited mixin scheme. It has become a good solution. Mixin is mainly used to solve the reuse problem of life cycle logic and state logic, and allows the component life cycle to be extended from the outside. This is especially important in Flux and other modes, but many defects have also appeared in continuous practice:</p>\n<ul>\n<li>There is an implicit dependency between the component and the mixin (Mixin often depends on the specific method of the component, but the dependency is not known when the component is defined).</li>\n<li>There may be conflicts between multiple mixin (such as defining the same state field).</li>\n<li>Mixin tends to add more states, which reduces the predictability of the application and leads to a sharp increase in complexity.</li>\n<li>Implicit dependencies lead to opaque dependencies, and maintenance costs and understanding costs are rising rapidly.</li>\n<li>It is difficult to quickly understand the behavior of components, and it is necessary to fully understand all the extension behaviors that rely on mixin and their mutual influence.</li>\n<li>The method and state field of the component itself is afraid to be easily deleted because it is difficult to determine whether mixin depends on it.</li>\n<li>Mixin is also difficult to maintain, because Mixin logic will eventually be flattened and merged together, and it is difficult to figure out the input and output of a Mixin.</li>\n</ul>\n<p>There is no doubt that these problems are fatal, so Reactv0.13.0 abandoned Mixin static crosscutting (similar to inherited reuse) and moved to HOC higher-order components (similar to combined reuse).</p>\n<h4>Example</h4>\n<p>The example of the ancient version, a common scenario is: A component needs to be updated regularly. It is easy to do it with setInterval(), but it is very important to cancel the timer when it is not needed to save memory. React provides a lifecycle method to inform the component. The time of creation or destruction, the following Mixin, use setInterval() and ensure that the timer is cleaned up when the component is destroyed.</p>\n<a href=\"https://medium.com/media/6fd5344ded564231f982182c4310121b/href\">https://medium.com/media/6fd5344ded564231f982182c4310121b/href</a><h3>HOC</h3>\n<p>After Mixin, HOC high-order components take on the heavy responsibility and become the recommended solution for logical reuse between components. High-order components reveal a high-order atmosphere from their names. In fact, this concept should be derived from high-order functions of JavaScript. The high-order function is a function that accepts a function as input or output. It can be thought that currying is a higher-order function. The definition of higher-order components is also given in the React document. Higher-order components receive components and return new components. function. The specific meaning is: High-order components can be seen as an implementation of React decoration pattern. High-order components are a function, and the function accepts a component as a parameter and returns a new component. It will return an enhanced React components. High-order components can make our code more reusable, logical and abstract, can hijack the render method, and can also control propsand state.</p>\n<p>Comparing Mixin and HOC, Mixin is a mixed-in mode. In actual use, Mixin is still very powerful, allowing us to share the same method in multiple components, but it will also continue to add new methods and attributes to the components. The component itself can not only perceive but also need to do related processing (such as naming conflicts, state maintenance, etc.). Once the mixed modules increase, the entire component becomes difficult to maintain. Mixin may introduce invisible attributes, such as in the Mixin method used in the rendering component brings invisible property props and states to the component. Mixin may depend on each other and is coupled with each other, which is not conducive to code maintenance. In addition, the methods in different Mixin may conflict with each other. Previously React officially recommended using Mixin to solve problems related to cross-cutting concerns, but because using Mixin may cause more trouble, the official recommendation is now to use HOC. High-order component HOC belong to the idea of functional programming. The wrapped components will not be aware of the existence of high-order components, and the components returned by high-order components will have a functional enhancement effect on the original components. Based on this, React officially recommends the use of high-order components.</p>\n<p>Although HOC does not have so many fatal problems, it also has some minor flaws:</p>\n<ul>\n<li>Scalability restriction: HOC cannot completely replace Mixin. In some scenarios, Mixin can but HOC cannot. For example, PureRenderMixin, because HOC cannot access the State of subcomponents from the outside, and at the same time filter out unnecessary updates through shouldComponentUpdate. Therefore, React After supporting ES6Class, React.PureComponent is provided to solve this problem.</li>\n<li>Ref transfer problem: Ref is cut off. The transfer problem of Ref is quite annoying under the layers of packaging. The function Ref can alleviate part of it (allowing HOC to learn about node creation and destruction), so the React.forwardRef API API was introduced later.</li>\n<li>WrapperHell: HOC is flooded, and WrapperHell appears (there is no problem that cannot be solved by one layer, if there is, then two layers). Multi-layer abstraction also increases complexity and cost of understanding. This is the most critical defect. In HOC mode There is no good solution.</li>\n</ul>\n<h4>Example</h4>\n<p>Specifically, a high-order component is a function whose parameter is a component and the return value is a new component. A component converts props into a UI but a high-order component converts a component into another component. HOC is very common in React third-party libraries, such as Redux’s connect and Relay’s createFragmentContainer.</p>\n<a href=\"https://medium.com/media/90068090af75d82f09618a2e3b129735/href\">https://medium.com/media/90068090af75d82f09618a2e3b129735/href</a><p>Attention should be paid here, do not try to modify the component prototype in the HOC in any way, but should use the combination method to realize the function by packaging the component in the container component. Under normal circumstances, there are two ways to implement high-order components:</p>\n<ul>\n<li>Property agent Props Proxy.</li>\n<li>Reverse inheritance Inheritance Inversion.</li>\n</ul>\n<h4>Property Agent</h4>\n<p>For example, we can add a stored id attribute value to the incoming component. We can add a props to this component through high-order components. Of course, we can also operate on the props in the WrappedComponent component in JSX. Note that it is not to manipulate the incoming WrappedComponent class, we should not directly modify the incoming component, but can operate on it in the process of combination.</p>\n<a href=\"https://medium.com/media/49e24540e51916b4fb3de4aaabb24ed1/href\">https://medium.com/media/49e24540e51916b4fb3de4aaabb24ed1/href</a><p>We can also use high-order components to load the state of new components into the packaged components. For example, we can use high-order components to convert uncontrolled components into controlled components.</p>\n<a href=\"https://medium.com/media/c21c2997d27e3522421b423881bfa3a3/href\">https://medium.com/media/c21c2997d27e3522421b423881bfa3a3/href</a><p>Or our purpose is to wrap it with other components to achieve the purpose of layout or style.</p>\n<a href=\"https://medium.com/media/a67368bf8f443f35fa16cb084dd3581b/href\">https://medium.com/media/a67368bf8f443f35fa16cb084dd3581b/href</a><h4>Reverse inheritance</h4>\n<p>Reverse inheritance means that the returned component inherits the previous component. In reverse inheritance, we can do a lot of operations, modify state, props and even flip the Element Tree. There is an important point in the reverse inheritance that reverse inheritance cannot ensure that the complete sub-component tree is parsed. That means if the parsed element tree contains components (function type or Class type), the sub-components of the component can no longer be manipulated.</p>\n<p>When we use reverse inheritance to implement high-order components, we can control rendering through rendering hijacking. Specifically, we can consciously control the rendering process of WrappedComponent to control the results of rendering control. For example, we can decide whether to render components according to some parameters.</p>\n<a href=\"https://medium.com/media/2f51f1a2e79f2d530f865980dba2158b/href\">https://medium.com/media/2f51f1a2e79f2d530f865980dba2158b/href</a><p>We can even hijack the life cycle of the original component by rewriting.</p>\n<a href=\"https://medium.com/media/d0d1d1a2e3655228e9e6214117d3fa91/href\">https://medium.com/media/d0d1d1a2e3655228e9e6214117d3fa91/href</a><p>Since it is actually an inheritance relationship, we can read the props and state of the component. If necessary, we can even add, modify, and delete the props and state. Of course, the premise is that the risks caused by the modification need to be controlled by yourself. In some cases, we may need to pass in some parameters for the high-order attributes, then we can pass in the parameters in the form of currying, and cooperate with the high-order components to complete the operation similar to the closure of the component.</p>\n<a href=\"https://medium.com/media/c93764203e66ee528fa2590b469fe091/href\">https://medium.com/media/c93764203e66ee528fa2590b469fe091/href</a><h4>note</h4>\n<p><strong>Don’t change the original components</strong></p>\n<p>Don’t try to modify the component prototype in HOC, or change it in other ways.</p>\n<a href=\"https://medium.com/media/38ab4b11e2b2e2bd581eca1ce0cfc6e6/href\">https://medium.com/media/38ab4b11e2b2e2bd581eca1ce0cfc6e6/href</a><p>Doing so will have some undesirable consequences. One is that the input component can no longer be used as before the HOC enhancement. What is more serious is that if you use another HOC that also modifies componentDidUpdate to enhance it, the previous HOC will be invalid, and this HOC cannot be applied to functional components that have no life cycle.<br>Modifying the HOC of the incoming component is a bad abstraction, and the caller must know how they are implemented to avoid conflicts with other HOC. HOC should not modify the incoming components, but should use a combination of components to achieve functions by packaging the components in container components.</p>\n<a href=\"https://medium.com/media/9d539457779e7022762037d655c757e3/href\">https://medium.com/media/9d539457779e7022762037d655c757e3/href</a><p><strong>Filter props</strong></p>\n<p>HOC adds features to components and should not significantly change the convention itself. The components returned by HOC should maintain similar interfaces with the original components. HOC should transparently transmit props that have nothing to do with itself, and most HOC should include a render method similar to the following.</p>\n<a href=\"https://medium.com/media/674a9a7a926cee12af9dbd9e6423db36/href\">https://medium.com/media/674a9a7a926cee12af9dbd9e6423db36/href</a><p><strong>Maximum composability</strong></p>\n<p>Not all HOCs are the same. Sometimes it only accepts one parameter, which is the packaged component.</p>\n<pre>const NavbarWithRouter = withRouter(Navbar);</pre>\n<p>HOC can usually receive multiple parameters. For example, in Relay, HOC additionally receives a configuration object to specify the data dependency of the component.</p>\n<pre>const CommentWithRelay = Relay.createContainer(Comment, config);</pre>\n<p>The most common HOC signatures are as follows, connect is a higher-order function that returns higher-order components.</p>\n<a href=\"https://medium.com/media/590de18c82ad90e07cf1f8fed23a9845/href\">https://medium.com/media/590de18c82ad90e07cf1f8fed23a9845/href</a><p>This form may seem confusing or unnecessary, but it has a useful property, like the single-parameter HOC returned by the connect function has the signature Component => Component , and functions with the same output type and input type can be easily combined. The same attributes also allow connect and other HOCs to assume the role of decorator. In addition, many third-party libraries provide compose tool functions, including lodash, Redux, and Ramda.</p>\n<a href=\"https://medium.com/media/9cbc152eb50e35834c4d012ba48bfdbe/href\">https://medium.com/media/9cbc152eb50e35834c4d012ba48bfdbe/href</a><p><strong>Don’t use HOC in the render method</strong></p>\n<p>React ’s diff algorithm uses the component identifier to determine whether it should update the existing subtree or discard it and mount the new subtree. If the component returned from the render is the same as the component in the previous render ===, React passes The subtree is distinguished from the new subtree to recursively update the subtree, and if they are not equal, the previous subtree is completely unloaded.<br>Usually, you don’t need to consider this when using it, but it is very important for HOC, because it means that you should not apply HOC to a component in the render method of the component.</p>\n<a href=\"https://medium.com/media/01ec9da706301817b5d6ae40a4748a33/href\">https://medium.com/media/01ec9da706301817b5d6ae40a4748a33/href</a><p>This is not just a performance issue. Re-mounting the component will cause the state of the component and all its subcomponents to be lost. If the HOC is created outside the component, the component will only be created once. So every time you render it will be the same component. Generally speaking, this is consistent with your expected performance. In rare cases, you need to call HOC dynamically, you can call it in the component’s lifecycle method or its constructor.</p>\n<p><strong>Be sure to copy static methods</strong></p>\n<p>Sometimes it is useful to define static methods on React components. For example, the Relay container exposes a static method getFragment to facilitate the composition of GraphQL fragments. But when you apply HOC to a component, the original component will be packaged with a container component, which means that the new component does not have any static methods of the original component.</p>\n<a href=\"https://medium.com/media/efea68083923fe3dd728247948db447f/href\">https://medium.com/media/efea68083923fe3dd728247948db447f/href</a><p>To solve this problem, you can copy these methods to the container component before returning.</p>\n<a href=\"https://medium.com/media/9abac726b9373ce25fce08cf13c3fc22/href\">https://medium.com/media/9abac726b9373ce25fce08cf13c3fc22/href</a><p>But to do this, you need to know which methods should be copied. You can use hoist-non-react-statics to automatically copy all non-React static methods.</p>\n<a href=\"https://medium.com/media/791281382a5f23b7de315432be7c3aab/href\">https://medium.com/media/791281382a5f23b7de315432be7c3aab/href</a><p>In addition to exporting components, another feasible solution is to additionally export this static method.</p>\n<a href=\"https://medium.com/media/3d9ffdbc5203c4e03a2864d4b6ceadcb/href\">https://medium.com/media/3d9ffdbc5203c4e03a2864d4b6ceadcb/href</a><p><strong>Refs will not be passed</strong></p>\n<p>Although the convention of high-level components is to pass all props to the packaged component, this does not apply to refs, because ref is not actually a prop, just like a key, it is specifically handled by React. If the ref is added to the return component of the HOC, the ref reference points to the container component, not the packaged component. This problem can be explicitly forwarded to the internal component through the React.forwardRefAPI refs.</p>\n<a href=\"https://medium.com/media/b2badf123b0fde8ea364b52fc69fb78c/href\">https://medium.com/media/b2badf123b0fde8ea364b52fc69fb78c/href</a><h3>Render Props</h3>\n<p>Like HOC, Render props is also a veteran model that has always existed. render props refers to a simple technology that uses a props valued as a function to share code between a kind of React components. A component with render props receives a function. This function Return a React element and call it instead of implementing its own rendering logic. Render props is a function props used to tell the component what content needs to be rendered. It is also a way to implement component logic reuse. Simply put, it is being copied. In the component used, pass a prop property named render (the property name may not render, as long as the value is a function). The property is a function. This function accepts an object and returns a subcomponent, which will The object in the function parameter is passed as props to the newly generated component, and when using the caller component, you only need to decide where to renderthe component and what logic to renderand pass in the relevant object.<br>Comparing HOC and Render props, technically, both are based on the component combination mechanism. Render props has the same extensibility as HOC. It is called Render props. It does not mean that it can only be used to reuse rendering logic, but that it is here. In this mode, the components are combined through render(), similar to the establishment of a combination relationship through Wrapper’s render() in HOC mode. The two are very similar, and they will also produce a layer of Wrapper. In fact, Render props and HOC . It can even be converted to each other.<br>Similarly, Render props will have some problems:</p>\n<ul>\n<li>The data flow is more intuitive. The descendant components can clearly see the source of the data, but in essence, Render props is implemented based on closures. A large number of component reuse will inevitably introduce the callback hell problem.</li>\n<li>The context of the component is lost, so there is no this.propsproperty, and this.props.childern cannot be accessed like HOC.</li>\n</ul>\n<a href=\"https://medium.com/media/64a91bfecbecd6c5b4769f5780282dbb/href\">https://medium.com/media/64a91bfecbecd6c5b4769f5780282dbb/href</a><h3>Hooks</h3>\n<p>There are endless code reuse solutions, but overall code reuse is still very complicated. A large part of this is because fine-grained code reuse should not be bundled with component reuse. HOC, Render props, etc. are based on component combination The solution is equivalent to first packaging the logic to be reused into components, and then using the component reuse mechanism to achieve logic reuse. Naturally, it is limited to component reuse, so there are problems such as limited scalability, Ref partition, Wrapper Hell, etc. , Then we need to have a simple and direct way of code reuse. Functions. Separating reusable logic into functions should be the most direct and cost-effective way of code reuse. But for state logic, some abstract patterns are still needed. (Such as Observable) can be reused, which is exactly the idea of Hooks, using functions as the smallest code reuse unit, and built-in some modes to simplify the reuse of state logic. Compared with the other solutions mentioned above, Hooks makes the logic reuse within the component no longer bundled with the component reuse. It is really trying to solve the problem of fine-grained logic reuse (between components) from the lower level. In addition, this statement The modular logic reuse scheme further extends the explicit data flow and combination ideas between components to the components.<br>File Hooks are not perfect either, but for now, its disadvantages are as follows:</p>\n<ul>\n<li>The additional learning cost mainly lies in the comparison between Functional Component and Class Component .</li>\n<li>There are restrictions on the writing method (cannot appear in conditions, loops), and the writing restrictions increase the cost of reconstruction.</li>\n<li>It destroys the performance optimization effect of PureComponent and React.memo shallow comparison. In order to get the latest props and state, the event function must be recreated every render()</li>\n<li>In closure scenarios, old state and props values may be referenced.</li>\n<li>The internal implementation is not intuitive, relying on a mutable global state, and no longer so pure.</li>\n<li>React.memo can’t completely replace shouldComponentUpdate (because state change is not available, only for props change).</li>\n<li>The useStateAPI is not perfect in design.</li>\n</ul>\n<a href=\"https://medium.com/media/6b1308a30a4cc6f973b8276a25aec06d/href\">https://medium.com/media/6b1308a30a4cc6f973b8276a25aec06d/href</a><img src=\"https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=851ffcc68a9c\" width=\"1\" height=\"1\" alt=\"\"><hr>\n<p><a href=\"https://medium.com/codezillas/how-to-reuse-react-components-851ffcc68a9c\">How To Reuse React Components</a> was originally published in <a href=\"https://medium.com/codezillas\">Codezillas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>\n",
"enclosure": {},
"categories": [
"front-end-development",
"programming",
"javascript",
"react",
"web-development"
],
"clapCount": 52,
"voterCount": 10,
"responseCount": 0,
"readingTime": 12
},
{
"title": "Explore Clipboard Operation in JavaScript",
"pubDate": "2021-03-22 08:02:38",
"link": "https://medium.com/geekculture/explore-clipboard-operation-in-javascript-c6399619c0ac?source=rss-b255948cc1f5------2",
"guid": "https://medium.com/p/c6399619c0ac",
"author": "Sabesan Sathananthan",
"thumbnail": "https://cdn-images-1.medium.com/max/1024/1*5NqK_GvOb0buWsDmDUvWkg.jpeg",
"description": "\n<h4>Cut, Copy and Paste in JavaScript</h4>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*5NqK_GvOb0buWsDmDUvWkg.jpeg\"><figcaption>Photo by <a href=\"https://www.pexels.com/@alex-green?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels\">Alex Green</a> from <a href=\"https://www.pexels.com/photo/crop-interviewer-writing-in-notepad-and-talking-to-job-seeker-5699480/?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels\">Pexels</a></figcaption></figure><p>The browser allows JavaScript scripts to read and write to the clipboard, and automatically copy or paste content. In general, scripts should not modify the user’s clipboard, so as not to meet the user’s expectations. However, sometimes it can be convenient to do this, such as the “one-click copy” function, the user clicks a button, and the specified content is automatically entered into the clipboard. Currently, there are three ways to implement clipboard operations.</p>\n<ul>\n<li>Document.execCommand()method</li>\n<li>Asynchronous Clipboard API</li>\n<li>copy,cut and paste Events</li>\n</ul>\n<p>This article introduces these three methods one by one. This is my 37th Medium article.</p>\n<h3>Document.execCommand() method</h3>\n<p>Document.execCommand() is the traditional method of manipulating the clipboard, which is supported by various browsers. It supports the three operations of copy, cut, and paste.</p>\n<ul>\n<li>Document.execCommand('copy') — copy</li>\n<li>Document.execCommand('cut') — cut</li>\n<li>Document.execCommand('paste') — paste</li>\n</ul>\n<h4>Copy or Cut operation</h4>\n<p>When copying, first select the text and then call the Document.execCommand('copy'), the selected text will enter the clipboard.</p>\n<a href=\"https://medium.com/media/9d3d2c9d872794a6960dac276cdafef3/href\">https://medium.com/media/9d3d2c9d872794a6960dac276cdafef3/href</a><p>In the above example, the script first selects the text in the inputElement of the input box ( inputElement.select() ), and then Document.execCommand('copy') copies it to the clipboard. Note that the copy operation is best placed in the event listener function, triggered by the user (for example, the user clicks a button). If the script is executed autonomously, some browsers may report an error. Cut operation is also similar to the copy operation.</p>\n<a href=\"https://medium.com/media/2c370cdc565840fc90b9b2d114951405/href\">https://medium.com/media/2c370cdc565840fc90b9b2d114951405/href</a><h4>Paste operation</h4>\n<p>When pasting, calling Document.execCommand('paste') will output the contents of the clipboard to the current focus element.</p>\n<a href=\"https://medium.com/media/87c5e442a7018036dfc607514de7c9af/href\">https://medium.com/media/87c5e442a7018036dfc607514de7c9af/href</a><h4>Disadvantage</h4>\n<p>Although the Document.execCommand() method is convenient, it has some disadvantages. First, it can only copy the selected content to the clipboard, and cannot write content to the clipboard arbitrarily. Secondly, it is an asynchronous operation. If you copy/paste a large amount of data, the page will freeze. Some browsers will also pop up a prompt box and ask the user for permission. At this time, the page will become unresponsive before the user makes a choice. In order to solve these problems, browser vendors have proposed an asynchronous Clipboard API.</p>\n<h3>Asynchronous Clipboard API</h3>\n<p>Clipboard API is the next-generation clipboard operation method, which is more powerful and reasonable than the traditional Document.execCommand() method. All its operations are asynchronous and return Promise objects without causing page jams. Moreover, it can put arbitrary content (such as pictures) into the clipboard. The navigator.clipboard property returns the Clipboard object, and all operations are performed through this object.</p>\n<pre>const clipboardObj = navigator.clipboard;</pre>\n<p>If the navigator.clipboard property returns undefined, it means that the current browser does not support this API (you can see the full compatibly table on <a href=\"https://caniuse.com/async-clipboard\">Can I use</a>…). Since users may put sensitive data (such as passwords) on the clipboard, allowing scripts to read them arbitrarily will cause security risks, so this API has more security restrictions. First of all, the Chrome browser stipulates that only HTTPS protocol pages can use this API. However, the development environment (localhost) allows the use of non-encrypted protocols. Secondly, the user’s permission needs to be clearly obtained when calling. The specific implementation of permissions uses the Permissions API. There are two permissions related to the clipboard: clipboard-write (write permission) and clipboard-read (read permission). The “write permission” is automatically granted to the script, and the “read permission” must be explicitly granted by the user. In other words, the script can be automatically completed when writing to the clipboard, but when reading the clipboard, the browser will pop up a dialog box asking whether the user agrees to read.</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/810/1*fmmX3ymNeN4iSPfG8UU1QA.png\"><figcaption>The permission prompt for the Clipboard API.</figcaption></figure><p>In addition, it should be noted that what the script reads is always the clipboard of the current page. One problem that this brings is that if you paste the relevant code into the developer tool and run it directly, an error may be reported because the current page at this time is the window of the developer tool, not a web page.</p>\n<a href=\"https://medium.com/media/c917e180df44ce0caf0e422b013fb7c6/href\">https://medium.com/media/c917e180df44ce0caf0e422b013fb7c6/href</a><p>If you paste the above code into the developer tool and run it, an error will be reported. Because when the code is running, the developer tool window is the current page, and there is no DOM interface that the Clipboard API depends on this page. One solution is to put the relevant code in setTimeout() to delay running, and quickly click on the page window of the browser before calling the function to turn it into the current page.</p>\n<a href=\"https://medium.com/media/d4a86d5bd7042b55a12b262e7de204b8/href\">https://medium.com/media/d4a86d5bd7042b55a12b262e7de204b8/href</a><p>After the above code is pasted into the developer tool to run, quickly click on the page window of the webpage to make it the current page, so that no error will be reported.</p>\n<h4>Clipboard object</h4>\n<p><strong>clipboard.readText()</strong></p>\n<p>The clipboard.readText() method is used to copy the text data in the clipboard.</p>\n<a href=\"https://medium.com/media/edbdd6afe11db16aef6fd8cf2a5de380/href\">https://medium.com/media/edbdd6afe11db16aef6fd8cf2a5de380/href</a><p>In the above example, after the user clicks on the page, the text in the clipboard will be output. Note that the browser will pop up a dialog box at this time, asking the user whether to agree with the script to read the clipboard.</p>\n<p>If the user disagrees, the script will report an error. At this time, you can use the try...catch structure to handle errors.</p>\n<a href=\"https://medium.com/media/7c30cda146134fe78fac02686240a822/href\">https://medium.com/media/7c30cda146134fe78fac02686240a822/href</a><p><strong>clipboard.read()</strong></p>\n<p>The clipboard.read() method is used to copy the data in the clipboard, which can be text data or binary data (such as pictures). This method requires explicit permission from the user. This method returns a Promise object. Once the state of the object becomes resolved, an array can be obtained, and each array member is an instance of a ClipboardItem object.</p>\n<a href=\"https://medium.com/media/5cfc2aab31a340fb24537d54448883e5/href\">https://medium.com/media/5cfc2aab31a340fb24537d54448883e5/href</a><p>The ClipboardItem object represents a single clip item and each clip item has a clipboardItem.types property and a clipboardItem.getType() method. The clipboardItem.types property returns an array whose members are the MIME types available for the clip item. For example, a clip item can be pasted in HTML format or in plain text format. Then it has two MIME types (text/html and text/plain). The clipboardItem.getType(type) method is used to read the data of the clip item and returns a Promise object. This method accepts the MIME type of the clip item as a parameter and returns the data of that type. This parameter is required, otherwise, an error will be reported.</p>\n<p><strong>clipboard.writeText()</strong></p>\n<p>The clipboard.writeText() method is used to write text content to the clipboard.</p>\n<a href=\"https://medium.com/media/b2786f780145c34da1d8d8b5f9970b7a/href\">https://medium.com/media/b2786f780145c34da1d8d8b5f9970b7a/href</a><p>The above example is that after the user clicks on the web page, the script writes text data to the clipboard. This method does not require user permission, but it is best to put it in try...catch to prevent errors.</p>\n<a href=\"https://medium.com/media/5b8e90947eaf99a062e9f43615c2fb1d/href\">https://medium.com/media/5b8e90947eaf99a062e9f43615c2fb1d/href</a><p><strong>clipboard.write()</strong></p>\n<p>The clipboard.write() method is used to write arbitrary data to the clipboard, which can be text data or binary data. This method accepts a ClipboardItem instance as a parameter, which represents the data written to the clipboard.</p>\n<a href=\"https://medium.com/media/1e4d8b9a0faa7aa9e8a6e4b84bd23a91/href\">https://medium.com/media/1e4d8b9a0faa7aa9e8a6e4b84bd23a91/href</a><p>In the above example, the script writes a picture to the clipboard. Note that the Chrome browser currently (until this writer writes this article) only supports writing images in PNG format. clipboardItem() is a constructor natively provided by the browser to generate an instance of clipboardItem. It accepts an object as a parameter. The key name of the object is the MIME type of the data, and the key value is the data itself. The following example is to write the value of the same clip item in multiple formats to the clipboard, one is text data, and the other is binary data for pasting on different occasions.</p>\n<a href=\"https://medium.com/media/4f89456ef61ba1676c74565508e34724/href\">https://medium.com/media/4f89456ef61ba1676c74565508e34724/href</a><h3>Copy, Cut, and Paste Events</h3>\n<p>When the user puts data into the clipboard, the copy event will be triggered. The following example is to convert the text that the user puts on the clipboard to uppercase.</p>\n<a href=\"https://medium.com/media/56349f2db4f9a0c68d50bfbd1e7b8e7d/href\">https://medium.com/media/56349f2db4f9a0c68d50bfbd1e7b8e7d/href</a><p>In the above example, the clipboardData property of the event object contains the clipboard data. It is an object with the following properties and methods.</p>\n<ul>\n<li>Event.clipboardData.setData(type, data) : To modify the clipboard data, you need to specify the data type.</li>\n<li>Event.clipboardData.getData(type) : To obtain clipboard data, you need to specify the data type.</li>\n<li>Event.clipboardData.clearData([type]) : Clear clipboard data, you can specify the data type. If you do not specify the type, all types of data will be cleared.</li>\n<li>Event.clipboardData.items : An array-like object contains all clip items, but usually there is only one clip item</li>\n</ul>\n<p>The following example is to intercept the user’s copy operation and put the specified content into the clipboard.</p>\n<a href=\"https://medium.com/media/4c39a1a4f6b3efcf4b47960f1f287627/href\">https://medium.com/media/4c39a1a4f6b3efcf4b47960f1f287627/href</a><p>In the above example, first, use e.preventDefault() to cancel the default operation of the clipboard, and then the script takes over the copy operation. The cut event is triggered when the user performs a cutting operation. Its processing is exactly the same as the copy event, and the cut data is also obtained from the Event.clipboardData property.</p>\n<p>When the user uses the clipboard data to paste, the paste event will be triggered. The following example is to intercept the paste operation, the data in the clipboard is taken out by the script.</p>\n<a href=\"https://medium.com/media/6aab8e207fccce5d7e966d382c2050b0/href\">https://medium.com/media/6aab8e207fccce5d7e966d382c2050b0/href</a><h3>Conclusion</h3>\n<p>For user experience, Clipboard access is a great tool. But Clipboard access has its thorns. Some users bring malicious data and some users carry sensitive data. Make sure you handle other user’s data responsibly. You need to prepare yourself for those nasty paste events.</p>\n<p>Asynchronous Clipboard API is new, and no browser supports all features, but it’s easier to use and more robust than the old Document.execCommand() method.</p>\n<img src=\"https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6399619c0ac\" width=\"1\" height=\"1\" alt=\"\"><hr>\n<p><a href=\"https://medium.com/geekculture/explore-clipboard-operation-in-javascript-c6399619c0ac\">Explore Clipboard Operation in JavaScript</a> was originally published in <a href=\"https://medium.com/geekculture\">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>\n",
"content": "\n<h4>Cut, Copy and Paste in JavaScript</h4>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*5NqK_GvOb0buWsDmDUvWkg.jpeg\"><figcaption>Photo by <a href=\"https://www.pexels.com/@alex-green?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels\">Alex Green</a> from <a href=\"https://www.pexels.com/photo/crop-interviewer-writing-in-notepad-and-talking-to-job-seeker-5699480/?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels\">Pexels</a></figcaption></figure><p>The browser allows JavaScript scripts to read and write to the clipboard, and automatically copy or paste content. In general, scripts should not modify the user’s clipboard, so as not to meet the user’s expectations. However, sometimes it can be convenient to do this, such as the “one-click copy” function, the user clicks a button, and the specified content is automatically entered into the clipboard. Currently, there are three ways to implement clipboard operations.</p>\n<ul>\n<li>Document.execCommand()method</li>\n<li>Asynchronous Clipboard API</li>\n<li>copy,cut and paste Events</li>\n</ul>\n<p>This article introduces these three methods one by one. This is my 37th Medium article.</p>\n<h3>Document.execCommand() method</h3>\n<p>Document.execCommand() is the traditional method of manipulating the clipboard, which is supported by various browsers. It supports the three operations of copy, cut, and paste.</p>\n<ul>\n<li>Document.execCommand('copy') — copy</li>\n<li>Document.execCommand('cut') — cut</li>\n<li>Document.execCommand('paste') — paste</li>\n</ul>\n<h4>Copy or Cut operation</h4>\n<p>When copying, first select the text and then call the Document.execCommand('copy'), the selected text will enter the clipboard.</p>\n<a href=\"https://medium.com/media/9d3d2c9d872794a6960dac276cdafef3/href\">https://medium.com/media/9d3d2c9d872794a6960dac276cdafef3/href</a><p>In the above example, the script first selects the text in the inputElement of the input box ( inputElement.select() ), and then Document.execCommand('copy') copies it to the clipboard. Note that the copy operation is best placed in the event listener function, triggered by the user (for example, the user clicks a button). If the script is executed autonomously, some browsers may report an error. Cut operation is also similar to the copy operation.</p>\n<a href=\"https://medium.com/media/2c370cdc565840fc90b9b2d114951405/href\">https://medium.com/media/2c370cdc565840fc90b9b2d114951405/href</a><h4>Paste operation</h4>\n<p>When pasting, calling Document.execCommand('paste') will output the contents of the clipboard to the current focus element.</p>\n<a href=\"https://medium.com/media/87c5e442a7018036dfc607514de7c9af/href\">https://medium.com/media/87c5e442a7018036dfc607514de7c9af/href</a><h4>Disadvantage</h4>\n<p>Although the Document.execCommand() method is convenient, it has some disadvantages. First, it can only copy the selected content to the clipboard, and cannot write content to the clipboard arbitrarily. Secondly, it is an asynchronous operation. If you copy/paste a large amount of data, the page will freeze. Some browsers will also pop up a prompt box and ask the user for permission. At this time, the page will become unresponsive before the user makes a choice. In order to solve these problems, browser vendors have proposed an asynchronous Clipboard API.</p>\n<h3>Asynchronous Clipboard API</h3>\n<p>Clipboard API is the next-generation clipboard operation method, which is more powerful and reasonable than the traditional Document.execCommand() method. All its operations are asynchronous and return Promise objects without causing page jams. Moreover, it can put arbitrary content (such as pictures) into the clipboard. The navigator.clipboard property returns the Clipboard object, and all operations are performed through this object.</p>\n<pre>const clipboardObj = navigator.clipboard;</pre>\n<p>If the navigator.clipboard property returns undefined, it means that the current browser does not support this API (you can see the full compatibly table on <a href=\"https://caniuse.com/async-clipboard\">Can I use</a>…). Since users may put sensitive data (such as passwords) on the clipboard, allowing scripts to read them arbitrarily will cause security risks, so this API has more security restrictions. First of all, the Chrome browser stipulates that only HTTPS protocol pages can use this API. However, the development environment (localhost) allows the use of non-encrypted protocols. Secondly, the user’s permission needs to be clearly obtained when calling. The specific implementation of permissions uses the Permissions API. There are two permissions related to the clipboard: clipboard-write (write permission) and clipboard-read (read permission). The “write permission” is automatically granted to the script, and the “read permission” must be explicitly granted by the user. In other words, the script can be automatically completed when writing to the clipboard, but when reading the clipboard, the browser will pop up a dialog box asking whether the user agrees to read.</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/810/1*fmmX3ymNeN4iSPfG8UU1QA.png\"><figcaption>The permission prompt for the Clipboard API.</figcaption></figure><p>In addition, it should be noted that what the script reads is always the clipboard of the current page. One problem that this brings is that if you paste the relevant code into the developer tool and run it directly, an error may be reported because the current page at this time is the window of the developer tool, not a web page.</p>\n<a href=\"https://medium.com/media/c917e180df44ce0caf0e422b013fb7c6/href\">https://medium.com/media/c917e180df44ce0caf0e422b013fb7c6/href</a><p>If you paste the above code into the developer tool and run it, an error will be reported. Because when the code is running, the developer tool window is the current page, and there is no DOM interface that the Clipboard API depends on this page. One solution is to put the relevant code in setTimeout() to delay running, and quickly click on the page window of the browser before calling the function to turn it into the current page.</p>\n<a href=\"https://medium.com/media/d4a86d5bd7042b55a12b262e7de204b8/href\">https://medium.com/media/d4a86d5bd7042b55a12b262e7de204b8/href</a><p>After the above code is pasted into the developer tool to run, quickly click on the page window of the webpage to make it the current page, so that no error will be reported.</p>\n<h4>Clipboard object</h4>\n<p><strong>clipboard.readText()</strong></p>\n<p>The clipboard.readText() method is used to copy the text data in the clipboard.</p>\n<a href=\"https://medium.com/media/edbdd6afe11db16aef6fd8cf2a5de380/href\">https://medium.com/media/edbdd6afe11db16aef6fd8cf2a5de380/href</a><p>In the above example, after the user clicks on the page, the text in the clipboard will be output. Note that the browser will pop up a dialog box at this time, asking the user whether to agree with the script to read the clipboard.</p>\n<p>If the user disagrees, the script will report an error. At this time, you can use the try...catch structure to handle errors.</p>\n<a href=\"https://medium.com/media/7c30cda146134fe78fac02686240a822/href\">https://medium.com/media/7c30cda146134fe78fac02686240a822/href</a><p><strong>clipboard.read()</strong></p>\n<p>The clipboard.read() method is used to copy the data in the clipboard, which can be text data or binary data (such as pictures). This method requires explicit permission from the user. This method returns a Promise object. Once the state of the object becomes resolved, an array can be obtained, and each array member is an instance of a ClipboardItem object.</p>\n<a href=\"https://medium.com/media/5cfc2aab31a340fb24537d54448883e5/href\">https://medium.com/media/5cfc2aab31a340fb24537d54448883e5/href</a><p>The ClipboardItem object represents a single clip item and each clip item has a clipboardItem.types property and a clipboardItem.getType() method. The clipboardItem.types property returns an array whose members are the MIME types available for the clip item. For example, a clip item can be pasted in HTML format or in plain text format. Then it has two MIME types (text/html and text/plain). The clipboardItem.getType(type) method is used to read the data of the clip item and returns a Promise object. This method accepts the MIME type of the clip item as a parameter and returns the data of that type. This parameter is required, otherwise, an error will be reported.</p>\n<p><strong>clipboard.writeText()</strong></p>\n<p>The clipboard.writeText() method is used to write text content to the clipboard.</p>\n<a href=\"https://medium.com/media/b2786f780145c34da1d8d8b5f9970b7a/href\">https://medium.com/media/b2786f780145c34da1d8d8b5f9970b7a/href</a><p>The above example is that after the user clicks on the web page, the script writes text data to the clipboard. This method does not require user permission, but it is best to put it in try...catch to prevent errors.</p>\n<a href=\"https://medium.com/media/5b8e90947eaf99a062e9f43615c2fb1d/href\">https://medium.com/media/5b8e90947eaf99a062e9f43615c2fb1d/href</a><p><strong>clipboard.write()</strong></p>\n<p>The clipboard.write() method is used to write arbitrary data to the clipboard, which can be text data or binary data. This method accepts a ClipboardItem instance as a parameter, which represents the data written to the clipboard.</p>\n<a href=\"https://medium.com/media/1e4d8b9a0faa7aa9e8a6e4b84bd23a91/href\">https://medium.com/media/1e4d8b9a0faa7aa9e8a6e4b84bd23a91/href</a><p>In the above example, the script writes a picture to the clipboard. Note that the Chrome browser currently (until this writer writes this article) only supports writing images in PNG format. clipboardItem() is a constructor natively provided by the browser to generate an instance of clipboardItem. It accepts an object as a parameter. The key name of the object is the MIME type of the data, and the key value is the data itself. The following example is to write the value of the same clip item in multiple formats to the clipboard, one is text data, and the other is binary data for pasting on different occasions.</p>\n<a href=\"https://medium.com/media/4f89456ef61ba1676c74565508e34724/href\">https://medium.com/media/4f89456ef61ba1676c74565508e34724/href</a><h3>Copy, Cut, and Paste Events</h3>\n<p>When the user puts data into the clipboard, the copy event will be triggered. The following example is to convert the text that the user puts on the clipboard to uppercase.</p>\n<a href=\"https://medium.com/media/56349f2db4f9a0c68d50bfbd1e7b8e7d/href\">https://medium.com/media/56349f2db4f9a0c68d50bfbd1e7b8e7d/href</a><p>In the above example, the clipboardData property of the event object contains the clipboard data. It is an object with the following properties and methods.</p>\n<ul>\n<li>Event.clipboardData.setData(type, data) : To modify the clipboard data, you need to specify the data type.</li>\n<li>Event.clipboardData.getData(type) : To obtain clipboard data, you need to specify the data type.</li>\n<li>Event.clipboardData.clearData([type]) : Clear clipboard data, you can specify the data type. If you do not specify the type, all types of data will be cleared.</li>\n<li>Event.clipboardData.items : An array-like object contains all clip items, but usually there is only one clip item</li>\n</ul>\n<p>The following example is to intercept the user’s copy operation and put the specified content into the clipboard.</p>\n<a href=\"https://medium.com/media/4c39a1a4f6b3efcf4b47960f1f287627/href\">https://medium.com/media/4c39a1a4f6b3efcf4b47960f1f287627/href</a><p>In the above example, first, use e.preventDefault() to cancel the default operation of the clipboard, and then the script takes over the copy operation. The cut event is triggered when the user performs a cutting operation. Its processing is exactly the same as the copy event, and the cut data is also obtained from the Event.clipboardData property.</p>\n<p>When the user uses the clipboard data to paste, the paste event will be triggered. The following example is to intercept the paste operation, the data in the clipboard is taken out by the script.</p>\n<a href=\"https://medium.com/media/6aab8e207fccce5d7e966d382c2050b0/href\">https://medium.com/media/6aab8e207fccce5d7e966d382c2050b0/href</a><h3>Conclusion</h3>\n<p>For user experience, Clipboard access is a great tool. But Clipboard access has its thorns. Some users bring malicious data and some users carry sensitive data. Make sure you handle other user’s data responsibly. You need to prepare yourself for those nasty paste events.</p>\n<p>Asynchronous Clipboard API is new, and no browser supports all features, but it’s easier to use and more robust than the old Document.execCommand() method.</p>\n<img src=\"https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6399619c0ac\" width=\"1\" height=\"1\" alt=\"\"><hr>\n<p><a href=\"https://medium.com/geekculture/explore-clipboard-operation-in-javascript-c6399619c0ac\">Explore Clipboard Operation in JavaScript</a> was originally published in <a href=\"https://medium.com/geekculture\">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>\n",
"enclosure": {},
"categories": [
"javascript-tips",
"web-development",
"development",
"javascript",
"technology"
],
"clapCount": 110,
"voterCount": 6,
"responseCount": 0,
"readingTime": 6
},
{
"title": "Why JavaScript Developers Should Prefer Axios Over Fetch",
"pubDate": "2021-02-24 18:30:16",
"link": "https://betterprogramming.pub/why-javascript-developers-should-prefer-axios-over-fetch-294b28a96e2c?source=rss-b255948cc1f5------2",
"guid": "https://medium.com/p/294b28a96e2c",
"author": "Sabesan Sathananthan",
"thumbnail": "https://cdn-images-1.medium.com/max/2600/1*9jZV8QRYZyvN7oX4cGLm0w.jpeg",
"description": "<div class=\"medium-feed-item\">\n<p class=\"medium-feed-image\"><a href=\"https://betterprogramming.pub/why-javascript-developers-should-prefer-axios-over-fetch-294b28a96e2c?source=rss-b255948cc1f5------2\"><img src=\"https://cdn-images-1.medium.com/max/2600/1*9jZV8QRYZyvN7oX4cGLm0w.jpeg\" width=\"2784\"></a></p>\n<p class=\"medium-feed-snippet\">Backward=compatibility, monitoring upload progress, and more</p>\n<p class=\"medium-feed-link\"><a href=\"https://betterprogramming.pub/why-javascript-developers-should-prefer-axios-over-fetch-294b28a96e2c?source=rss-b255948cc1f5------2\">Continue reading on Better Programming »</a></p>\n</div>",
"content": "<div class=\"medium-feed-item\">\n<p class=\"medium-feed-image\"><a href=\"https://betterprogramming.pub/why-javascript-developers-should-prefer-axios-over-fetch-294b28a96e2c?source=rss-b255948cc1f5------2\"><img src=\"https://cdn-images-1.medium.com/max/2600/1*9jZV8QRYZyvN7oX4cGLm0w.jpeg\" width=\"2784\"></a></p>\n<p class=\"medium-feed-snippet\">Backward=compatibility, monitoring upload progress, and more</p>\n<p class=\"medium-feed-link\"><a href=\"https://betterprogramming.pub/why-javascript-developers-should-prefer-axios-over-fetch-294b28a96e2c?source=rss-b255948cc1f5------2\">Continue reading on Better Programming »</a></p>\n</div>",
"enclosure": {},
"categories": [
"angular",
"react",
"javascript",
"programming",
"web-development"
],
"clapCount": 2106,
"voterCount": 581,
"responseCount": 11,
"readingTime": 6
},
{
"title": "Deep Insights Into JavaScript’s Fetch API",
"pubDate": "2021-01-12 15:26:07",
"link": "https://betterprogramming.pub/deep-insights-into-javascripts-fetch-api-e8e8203c0965?source=rss-b255948cc1f5------2",
"guid": "https://medium.com/p/e8e8203c0965",
"author": "Sabesan Sathananthan",
"thumbnail": "https://cdn-images-1.medium.com/max/1024/1*qxsdWXwYFkXZPawgMPeRuA.jpeg",
"description": "\n<h4>A deeper look at fetch</h4>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*qxsdWXwYFkXZPawgMPeRuA.jpeg\"><figcaption>Photo by <a href=\"https://unsplash.com/@robfuller?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Rob Fuller</a> on <a href=\"https://unsplash.com/s/photos/fetch?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Unsplash</a></figcaption></figure><p>Requesting resources from an API is a popular and nearly crucial feature required for building modern applications. Whether you have created your own API or you are implementing a third-party API, you need a way to create your requests without slowing down your application. fetch() is an upgraded version of XMLHttpRequest, used to make HTTP requests in JavaScript scripts. The main difference between Fetch and XMLHttpRequest is that the Fetch API uses Promises, hence avoiding callback hell. The fetch API is natively supported by all modern browsers except Internet Explorer. This article details its usage. This is my 35th Medium article.</p>\n<h3>Basic Usage</h3>\n<p>The function of fetch() is basically the same as XMLHttpRequest, but there are three main differences.</p>\n<ul>\n<li>fetch() uses promise instead of the callback function, so it greatly simplifies the writing and makes writing more concise.</li>\n<li>fetch() adopts modular design and the API is scattered across multiple objects (Response object, Request object, Headers object). By contrast, the API design of XMLHttpRequest is not very good — input, output, and status are all it has. It’s easy to write very messy code with the same interface management.</li>\n<li>fetch() processes data through a data stream (Stream object), which can be read in blocks, which is beneficial to improve website performance and reduce memory usage. It’s very useful for scenarios where large files are requested or the network speed is slow. The XMLHTTPRequest object does not support data streaming. All data must be stored in the cache. Block reading is not supported. You must wait for all to be obtained before spitting it out in one go.</li>\n</ul>\n<p>In terms of usage, fetch() accepts a URL string as a parameter, sends a GET request to the URL by default, and returns a Promise object. Its basic usage is as follows:</p>\n<a href=\"https://medium.com/media/4bdb533ec407713542fcfbd93624ba60/href\">https://medium.com/media/4bdb533ec407713542fcfbd93624ba60/href</a><p>Below is an example to get JSON data from the server:</p>\n<a href=\"https://medium.com/media/1d398d82007f6e3e6b39c518bc6af64b/href\">https://medium.com/media/1d398d82007f6e3e6b39c518bc6af64b/href</a><p>In the above example, the response received by fetch() is a Stream object, and response.json() is an asynchronous operation that takes out all the content and converts it into a JSON object. Promise can be rewritten using await syntax to make the semantics clearer.</p>\n<a href=\"https://medium.com/media/eeaa50abcf5c3473bf346aef3a7442ca/href\">https://medium.com/media/eeaa50abcf5c3473bf346aef3a7442ca/href</a><p>In the above example, the await statement must be placed inside the try...catch, to catch errors that may occur in asynchronous operations. The following text uses the wording await instead of of .then().</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*FgPdG2k7_uK-49xh6ZKz1g.jpeg\"><figcaption>Photo by <a href=\"https://unsplash.com/@sigmund?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Sigmund</a> on <a href=\"https://unsplash.com/s/photos/basic?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Unsplash</a></figcaption></figure><h3>Response Object: Handle HTTP Response</h3>\n<h4>Synchronous properties of the Response object</h4>\n<p>After the fetch() request is successful, you get a <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Response\">Response object</a>. It corresponds to the HTTP response of the server.</p>\n<pre>const response = await fetch(url);</pre>\n<p>As mentioned earlier, the data contained in Response is read asynchronously through the Stream interface, but it also contains some synchronous attributes, which correspond to the header information of the HTTP response (Headers), which can be read immediately.</p>\n<a href=\"https://medium.com/media/9483b722e45e198ed079f223e5f814f0/href\">https://medium.com/media/9483b722e45e198ed079f223e5f814f0/href</a><p>In the above example, response.status and response.statusText are the synchronous attributes of Response and can be read immediately.</p>\n<h4>Response.ok</h4>\n<p>The Response.ok property returns a boolean value, indicating whether the request is successful, true corresponds to the HTTP request status code 200 to 299, and false corresponds to other status codes.</p>\n<h4>Response.status</h4>\n<p>The Response.status property returns a number indicating the status code of the HTTP response (for example, 200, indicating a successful request).</p>\n<h4>Response.statusText</h4>\n<p>The Response.statusText property returns a string representing the status information of the HTTP response (for example, after the request is successful, the server returns “OK”).</p>\n<h4>Response.url</h4>\n<p>The Response.url property returns the requested URL. If the URL has a redirect, this attribute returns the final URL.</p>\n<h4>Response.type</h4>\n<p>The Response.type property returns the type of request. The possible values are as follows:</p>\n<ul>\n<li>basic: Ordinary, same-origin request.</li>\n<li>cors: Cross-origin request.</li>\n<li>error: Network errors, mainly used for service workers.</li>\n<li>opaque: If the mode attribute of the fetch() request is set to no-cors, this response value will be returned.</li>\n<li>opaqueredirect: If the redirect attribute of the fetch() request is set to manual, this response value will be returned.</li>\n</ul>\n<h4>Response.redirected</h4>\n<p>The Response.redirected property returns a Boolean value, indicating whether the request has been redirected.</p>\n<h4>Determine whether the request is successful</h4>\n<p>After fetch() sends a request, there is an important point to note: fetch() will report an error only when there’s a network error or cannot connect. In other cases, no error will be reported, but the request is considered successful.</p>\n<p>This means, even if the status code returned by the server is 4xx or 5xx, fetch() will not report an error (i.e. The Promise will not become rejected). Only by obtaining the true status code of the HTTP response through the Responese.status property, can it be determined whether the request is successful. Please see the following example:</p>\n<a href=\"https://medium.com/media/665e65d487ce15d48d08a73360f19b99/href\">https://medium.com/media/665e65d487ce15d48d08a73360f19b99/href</a><p>In the above example, the Responese.status attribute must be equal to 2xx (200~299) to determine that the request is successful. There’s no need to consider the URL jump (status code is 3xx) because fetch() will automatically convert the jumped status code to 200. Another method is to determine whether Responese.ok is true.</p>\n<a href=\"https://medium.com/media/e81b4e8fa9088f3bfb356dac5f80ea77/href\">https://medium.com/media/e81b4e8fa9088f3bfb356dac5f80ea77/href</a><h4>Response.headers property</h4>\n<p>The Response object also has a Responese.headers property, which points to a <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Headers\">Headers object</a>, which corresponds to all the headers of the HTTP response. Headers objects can be traversed using for...of loops.</p>\n<a href=\"https://medium.com/media/e78e37a3391dfc7694b5b8e11c2c428f/href\">https://medium.com/media/e78e37a3391dfc7694b5b8e11c2c428f/href</a><p>The Headers object provides the following methods to manipulate headers.</p>\n<ul>\n<li>Headers.get(): According to the specified key name, return the key-value.</li>\n<li>Headers.has(): Returns a Boolean value indicating whether a header is included.</li>\n<li>Headers.set(): Set the specified key name as the new key-value, if the key name does not exist, it will be added.</li>\n<li>Headers.append(): Add headers.</li>\n<li>Headers.delete(): Delete the header.</li>\n<li>Headers.keys(): Return an iterator that can traverse all the keys in turn.</li>\n<li>Headers.values(): Return an iterator that can traverse all key values in turn.</li>\n<li>Headers.entries(): Return an iterator that can traverse all key-value pairs in turn ([key, value]).</li>\n<li>Headers.forEach(): Traverse the headers, in turn. Each header will execute a parameter function.</li>\n</ul>\n<p>Some of the above methods can modify the headers because they inherit from the Headers interface. For HTTP responses, modifying headers is of little significance — many headers are read-only and browsers do not allow modification. Among these methods, the most commonly used is response.headers.get(), which is used to read the value of a certain header.</p>\n<a href=\"https://medium.com/media/ef94b7cae6d85c73cc1b764fde4f69f4/href\">https://medium.com/media/ef94b7cae6d85c73cc1b764fde4f69f4/href</a><p>The Headers.keys() and Headers.values() methods are used to traverse the header keys and key values respectively.</p>\n<a href=\"https://medium.com/media/1c7222d472b0be159f8237f941948f55/href\">https://medium.com/media/1c7222d472b0be159f8237f941948f55/href</a><p>The Headers.forEach() method can also traverse all key values and key names.</p>\n<a href=\"https://medium.com/media/e9d0906865cf98625d23be25b8da9cb6/href\">https://medium.com/media/e9d0906865cf98625d23be25b8da9cb6/href</a><h4>How to read content</h4>\n<p>The Response object provides different reading methods according to different types of data returned by the server.</p>\n<ul>\n<li>response.text(): Get the text string.</li>\n<li>response.json(): Get the JSON object.</li>\n<li>response.blob(): Get the binary Blob object.</li>\n<li>response.formData(): Get the FormData object.</li>\n<li>response.arrayBuffer(): Get the binary ArrayBuffer object.</li>\n</ul>\n<p>The above five reading methods are all asynchronous and all return Promise objects. You must wait until the end of the asynchronous operation to get the complete data returned by the server.</p>\n<h4>response.text()</h4>\n<p>response.text() can be used to get text data, such as HTML files.</p>\n<a href=\"https://medium.com/media/3d36dae5c1bf9e5f73f079962ba59365/href\">https://medium.com/media/3d36dae5c1bf9e5f73f079962ba59365/href</a><h4>response.json()</h4>\n<p>response.json() is mainly used to get the JSON data returned by the server. The example has been given earlier.</p>\n<h4>response.formData()</h4>\n<p>response.formData() is mainly used in Service Worker to intercept the form submitted by the user, modify some data, and then submit it to the server.</p>\n<h4>response.blob()</h4>\n<p>response.blob() is used to get the binary file.</p>\n<a href=\"https://medium.com/media/5e8b79479ae09fe490d9af8b18487364/href\">https://medium.com/media/5e8b79479ae09fe490d9af8b18487364/href</a><p>The above example reads the flower.jpg image file and displays it on the web page.</p>\n<h4>response.arrayBuffer()</h4>\n<p>response.arrayBuffer() is mainly used to obtain streaming media files.</p>\n<a href=\"https://medium.com/media/603beeb2cb1d0cf35de90e584395cd5f/href\">https://medium.com/media/603beeb2cb1d0cf35de90e584395cd5f/href</a><p>The above example is an example where response.arrayBuffer() gets the audio file song.ogg and then plays it online.</p>\n<h4>Response.clone()</h4>\n<p>The Stream object can only be read once and it is gone after reading. This means that only one of the five reading methods in the previous section can be used, otherwise, an error will be reported.</p>\n<pre>let text = await response.text();<br>let json = await response.json(); // Report an error</pre>\n<p>The above example uses response.text() first and then reads the Stream. After calling response.json() later, there’s no content to read, so an error is reported. The Response object provides the response.clone() method, which creates a copy of the Response object and implements multiple reads.</p>\n<a href=\"https://medium.com/media/e4053a76f78fd84a7cd033f1b5165780/href\">https://medium.com/media/e4053a76f78fd84a7cd033f1b5165780/href</a><p>In the above example, response.clone() made a copy of the Response object and then read the same image twice. The Response object also has a Response.redirect() method, which is used to redirect the Response result to the specified URL. This method is generally only used in Service Worker, so I won’t introduce it here.</p>\n<h4>Response.body attribute</h4>\n<p>The Response.body property is the underlying interface exposed by the Response object. It returns a ReadableStream object for user operations. It can be used to read content in blocks. One application is to display the progress of the download.</p>\n<a href=\"https://medium.com/media/9790f3efe764db5fcf0b8f081e5c97fc/href\">https://medium.com/media/9790f3efe764db5fcf0b8f081e5c97fc/href</a><p>In the above example, the response.body.getReader() method returns an iterator. The read() method of this traverser returns an object each time, representing the content block read this time. The done attribute of this object is a boolean value, used to judge whether it has been read. The value attribute is an arrayBuffer array, which represents the content of the content block. The value.length attribute is the size of the current block.</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/689/1*x8Is0ZGUft6UHAD2gB6izw.png\"><figcaption><a href=\"https://www.bccfalna.com/ebooks/wp-content/uploads/ebooks/2018/12/HTTP-Hyper-Text-Transfer-Protocol-for-Webpage-%E2%80%93-Request-and-Response-Core-JSP-in-Hindi.png\">https://www.bccfalna.com/ebooks/wp-content/uploads/ebooks/2018/12/HTTP-Hyper-Text-Transfer-Protocol-for-Webpage-%E2%80%93-Request-and-Response-Core-JSP-in-Hindi.png</a></figcaption></figure><h3>The Second Parameter of fetch(): Custom HTTP Request</h3>\n<p>The first parameter of fetch() is the URL, and the second parameter can also be accepted as a configuration object to customize the HTTP request sent out.</p>\n<pre>fetch(url, optionObj)</pre>\n<p>The optionObj of the above command is the second parameter. The HTTP request method, header, and data body are all set in this object. Here are some examples.</p>\n<h4>POST request</h4>\n<a href=\"https://medium.com/media/f5721cf8da6184fd42b09b7b2c93969b/href\">https://medium.com/media/f5721cf8da6184fd42b09b7b2c93969b/href</a><p>In the above example, the configuration object uses three attributes:</p>\n<ul>\n<li>method:The HTTP request method, POST, DELETE, PUT are all set in this property.</li>\n<li>headers:An object used to customize the header of the HTTP request.</li>\n<li>body:The data body of the POST request.</li>\n</ul>\n<p>Note that some headers cannot be set by the headers attribute, such as Content-Length, Cookie, Host, etc. They are automatically generated by the browser and cannot be modified.</p>\n<h4>Submit JSON data</h4>\n<a href=\"https://medium.com/media/34c1e41244bd546e313ad068a7b1da0d/href\">https://medium.com/media/34c1e41244bd546e313ad068a7b1da0d/href</a><p>In the above example, the header Content-Type should be set to 'application/json;charset=utf-8'. Because the default is to send plain text, the default value of Content-Type is 'text/plain;charset=UTF-8'.</p>\n<h4>Submit form</h4>\n<a href=\"https://medium.com/media/b245ad01ebefc2f8afc027743eb48b14/href\">https://medium.com/media/b245ad01ebefc2f8afc027743eb48b14/href</a><h4>File upload</h4>\n<p>If there is a file selector in the form, you can use the writing of the previous example. The uploaded file is included in the entire form and submitted together. Another method is to add files with scripts, construct a form, and upload, please see the example below.</p>\n<a href=\"https://medium.com/media/68a39a247c1f0f525bfb0b1fd3a17a79/href\">https://medium.com/media/68a39a247c1f0f525bfb0b1fd3a17a79/href</a><p>When uploading a binary file, there’s no need to modify the Content-Type of the header — the browser will automatically set it.</p>\n<h4>Upload binary data directly</h4>\n<p>fetch() can also upload binary data directly, putting Blob or arrayBuffer data in the body attribute.</p>\n<a href=\"https://medium.com/media/1b51a79c5a17d1dd95c4e02c377c81fd/href\">https://medium.com/media/1b51a79c5a17d1dd95c4e02c377c81fd/href</a><h3>The Complete Configuration Object of Fetch() API</h3>\n<p>The completion of the second parameter of fetch() API is as follows:</p>\n<a href=\"https://medium.com/media/f425f83c3bab22560cde7e0b67be6810/href\">https://medium.com/media/f425f83c3bab22560cde7e0b67be6810/href</a><p>The bottom layer of the fetch() request uses the interface of the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Request/Request\">Request() object</a>. The parameters are exactly the same, so the above API is also the API of Request(). Among these attributes, headers, body, and method have been given examples before. The following is an introduction to other attributes.</p>\n<h4><strong>cache</strong></h4>\n<p>The cache attribute specifies how to handle the cache. The possible values are as follows:</p>\n<ul>\n<li>default:The default value is to find matching requests in the cache first.</li>\n<li>no-store:Request the remote server directly and do not update the cache.</li>\n<li>reload:Directly request the remote server and update the cache.</li>\n<li>no-cache:Compare the server resources with the local cache and use the server resources when there is a new version. Otherwise use the local cache.</li>\n<li>force-cache:Cache is the priority, and the remote server is only requested if there is no cache.</li>\n<li>only-if-cached:Only check the cache. If the cache does not exist, a 504 error will be returned.</li>\n</ul>\n<h4><strong>mode</strong></h4>\n<p>The mode attribute specifies the requested mode. The possible values are as follows:</p>\n<ul>\n<li>cors:The default value allows cross-domain requests.</li>\n<li>same-origin:Only same-origin requests are allowed.</li>\n<li>no-cors:The request method is limited to GET, POST and HEAD, and only a limited number of simple headers can be used, and cross-domain complex headers cannot be added, which is equivalent to the request that can be made by submitting the form.</li>\n</ul>\n<h4><strong>credentials</strong></h4>\n<p>The credentials attribute specifies whether to send cookies. The possible values are as follows:</p>\n<ul>\n<li>same-origin:By default, cookies are sent when requesting from the same origin, but not when requesting across domains.</li>\n<li>include:Regardless of same-origin requests or cross-domain requests, cookies are always sent.</li>\n<li>omit:Never send.</li>\n</ul>\n<p>For cross-domain requests to send cookies, the credentials attribute needs to be set to include.</p>\n<a href=\"https://medium.com/media/bffb2739ff4353cc61e58c7e7a321923/href\">https://medium.com/media/bffb2739ff4353cc61e58c7e7a321923/href</a><h4><strong>signal</strong></h4>\n<p>The signal attribute specifies an AbortSignal instance to cancel the fetch() request, see the next section for details.</p>\n<h4><strong>keepalive</strong></h4>\n<p>The keepalive attribute is used when the page is uninstalled to tell the browser to keep the connection in the background and continue to send data. A typical scenario is that when the user leaves the web page, the script submits some statistical information about the user’s behavior to the server. At this time, if the keepalive attribute is not used, the data may not be sent because the browser has uninstalled the page.</p>\n<a href=\"https://medium.com/media/9dffdfaa0bbe3c344cb5dc736f76751e/href\">https://medium.com/media/9dffdfaa0bbe3c344cb5dc736f76751e/href</a><h4><strong>redirect</strong></h4>\n<p>The redirect attribute specifies the processing method for HTTP redirects. The possible values are as follows:</p>\n<ul>\n<li>follow:By default, fetch() follows HTTP redirects.</li>\n<li>error:If a jump occurs, fetch() will report an error.</li>\n<li>manual:fetch() does not follow the HTTP redirection, but the response.url property will point to the new URL, and the response.redirected property will become true. The developer decides how to handle the redirection later.</li>\n</ul>\n<h4><strong>integrity</strong></h4>\n<p>The integrity attribute specifies a hash value to check whether the data returned by the HTTP response is equal to the preset hash value. For example, when downloading a file, check whether the SHA-256 hash value of the file matches to ensure that it has not been tampered with.</p>\n<a href=\"https://medium.com/media/c6f188005cff10daec2765764a53a2e9/href\">https://medium.com/media/c6f188005cff10daec2765764a53a2e9/href</a><h4><strong>referrer</strong></h4>\n<p>The referrer attribute is used to set the referrer header of the fetch() request. This attribute can be any string or an empty string (that is, no referrer header is sent).</p>\n<a href=\"https://medium.com/media/3740312ff7331a2dbc11faa017ad4f29/href\">https://medium.com/media/3740312ff7331a2dbc11faa017ad4f29/href</a><h4><strong>referrerPolicy</strong></h4>\n<p>The referrerPolicy attribute is used to set the rules of the Referrer header. The possible values are as follows:</p>\n<ul>\n<li>no-referrer-when-downgrade:The default value, the Referrer header is always sent, unless it is not sent when requesting HTTP resources from an HTTPS page.</li>\n<li>no-referrer:The Referrer header is not sent.</li>\n<li>origin:The Referrer header only contains the domain name, not the complete path.</li>\n<li>origin-when-cross-origin:The Referrer header of the same-origin request contains the complete path, and the cross-domain request only contains the domain name.</li>\n<li>same-origin:Cross-domain requests do not send Referrer, but same-source requests are sent.</li>\n<li>strict-origin:The Referrer header only contains the domain name. The Referrer header is not sent when the HTTPS page requests HTTP resources.</li>\n<li>strict-origin-when-cross-origin:The Referrer header contains the full path for the same-origin request, and only the domain name for the cross-domain request. This header is not sent when the HTTPS page requests HTTP resources.</li>\n<li>unsafe-url: No matter what the situation, always send the Referrer header.</li>\n</ul>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*8ELG0a7FoW2yu_UyRaTWrg.jpeg\"><figcaption>Photo by <a href=\"https://unsplash.com/@sigmund?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Sigmund</a> on <a href=\"https://unsplash.com/s/photos/complete-configuration?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Unsplash</a></figcaption></figure><h3>Cancel fetch() Request</h3>\n<p>After the fetch() request is sent, if you want to cancel halfway, you need to use the AbortController object:</p>\n<a href=\"https://medium.com/media/521a9ef7287385a7cef496fe50dcb562/href\">https://medium.com/media/521a9ef7287385a7cef496fe50dcb562/href</a><p>In the above example, first create an AbortController instance, then send a fetch() request. The signal property of the configuration object must specify that it receives the signal Controller.signal sent by the AbortController instance. The Controller.abort method is used to signal the cancellation. At this time, the abort event will be triggered. This event can be monitored, or you can determine whether the cancel signal has been sent through the Controller.signal.aborted property. The following is an example of automatically canceling the request after one second:</p>\n<a href=\"https://medium.com/media/7d789ec5bd43ae3b4d084a370d5db8a7/href\">https://medium.com/media/7d789ec5bd43ae3b4d084a370d5db8a7/href</a><figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*CSK0GdPArv3m1UFDLNJT1w.jpeg\"><figcaption>Photo by <a href=\"https://unsplash.com/@instagramfotografin?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Peggy Anke</a> on <a href=\"https://unsplash.com/s/photos/cancel-request?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Unsplash</a></figcaption></figure><h3>Conclusion</h3>\n<p>Here I described Fetch API usages, handle HTTP response, custom HTTP request, configuration object, and cancel requests in JavaScript. The Fetch API can be a bit overwhelming, but it’s absolutely vital as you continue to learn code in JavaScript.</p>\n<p>Happy coding!</p>\n<img src=\"https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8e8203c0965\" width=\"1\" height=\"1\" alt=\"\"><hr>\n<p><a href=\"https://betterprogramming.pub/deep-insights-into-javascripts-fetch-api-e8e8203c0965\">Deep Insights Into JavaScript’s Fetch API</a> was originally published in <a href=\"https://betterprogramming.pub/\">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>\n",
"content": "\n<h4>A deeper look at fetch</h4>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*qxsdWXwYFkXZPawgMPeRuA.jpeg\"><figcaption>Photo by <a href=\"https://unsplash.com/@robfuller?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Rob Fuller</a> on <a href=\"https://unsplash.com/s/photos/fetch?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Unsplash</a></figcaption></figure><p>Requesting resources from an API is a popular and nearly crucial feature required for building modern applications. Whether you have created your own API or you are implementing a third-party API, you need a way to create your requests without slowing down your application. fetch() is an upgraded version of XMLHttpRequest, used to make HTTP requests in JavaScript scripts. The main difference between Fetch and XMLHttpRequest is that the Fetch API uses Promises, hence avoiding callback hell. The fetch API is natively supported by all modern browsers except Internet Explorer. This article details its usage. This is my 35th Medium article.</p>\n<h3>Basic Usage</h3>\n<p>The function of fetch() is basically the same as XMLHttpRequest, but there are three main differences.</p>\n<ul>\n<li>fetch() uses promise instead of the callback function, so it greatly simplifies the writing and makes writing more concise.</li>\n<li>fetch() adopts modular design and the API is scattered across multiple objects (Response object, Request object, Headers object). By contrast, the API design of XMLHttpRequest is not very good — input, output, and status are all it has. It’s easy to write very messy code with the same interface management.</li>\n<li>fetch() processes data through a data stream (Stream object), which can be read in blocks, which is beneficial to improve website performance and reduce memory usage. It’s very useful for scenarios where large files are requested or the network speed is slow. The XMLHTTPRequest object does not support data streaming. All data must be stored in the cache. Block reading is not supported. You must wait for all to be obtained before spitting it out in one go.</li>\n</ul>\n<p>In terms of usage, fetch() accepts a URL string as a parameter, sends a GET request to the URL by default, and returns a Promise object. Its basic usage is as follows:</p>\n<a href=\"https://medium.com/media/4bdb533ec407713542fcfbd93624ba60/href\">https://medium.com/media/4bdb533ec407713542fcfbd93624ba60/href</a><p>Below is an example to get JSON data from the server:</p>\n<a href=\"https://medium.com/media/1d398d82007f6e3e6b39c518bc6af64b/href\">https://medium.com/media/1d398d82007f6e3e6b39c518bc6af64b/href</a><p>In the above example, the response received by fetch() is a Stream object, and response.json() is an asynchronous operation that takes out all the content and converts it into a JSON object. Promise can be rewritten using await syntax to make the semantics clearer.</p>\n<a href=\"https://medium.com/media/eeaa50abcf5c3473bf346aef3a7442ca/href\">https://medium.com/media/eeaa50abcf5c3473bf346aef3a7442ca/href</a><p>In the above example, the await statement must be placed inside the try...catch, to catch errors that may occur in asynchronous operations. The following text uses the wording await instead of of .then().</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*FgPdG2k7_uK-49xh6ZKz1g.jpeg\"><figcaption>Photo by <a href=\"https://unsplash.com/@sigmund?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Sigmund</a> on <a href=\"https://unsplash.com/s/photos/basic?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Unsplash</a></figcaption></figure><h3>Response Object: Handle HTTP Response</h3>\n<h4>Synchronous properties of the Response object</h4>\n<p>After the fetch() request is successful, you get a <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Response\">Response object</a>. It corresponds to the HTTP response of the server.</p>\n<pre>const response = await fetch(url);</pre>\n<p>As mentioned earlier, the data contained in Response is read asynchronously through the Stream interface, but it also contains some synchronous attributes, which correspond to the header information of the HTTP response (Headers), which can be read immediately.</p>\n<a href=\"https://medium.com/media/9483b722e45e198ed079f223e5f814f0/href\">https://medium.com/media/9483b722e45e198ed079f223e5f814f0/href</a><p>In the above example, response.status and response.statusText are the synchronous attributes of Response and can be read immediately.</p>\n<h4>Response.ok</h4>\n<p>The Response.ok property returns a boolean value, indicating whether the request is successful, true corresponds to the HTTP request status code 200 to 299, and false corresponds to other status codes.</p>\n<h4>Response.status</h4>\n<p>The Response.status property returns a number indicating the status code of the HTTP response (for example, 200, indicating a successful request).</p>\n<h4>Response.statusText</h4>\n<p>The Response.statusText property returns a string representing the status information of the HTTP response (for example, after the request is successful, the server returns “OK”).</p>\n<h4>Response.url</h4>\n<p>The Response.url property returns the requested URL. If the URL has a redirect, this attribute returns the final URL.</p>\n<h4>Response.type</h4>\n<p>The Response.type property returns the type of request. The possible values are as follows:</p>\n<ul>\n<li>basic: Ordinary, same-origin request.</li>\n<li>cors: Cross-origin request.</li>\n<li>error: Network errors, mainly used for service workers.</li>\n<li>opaque: If the mode attribute of the fetch() request is set to no-cors, this response value will be returned.</li>\n<li>opaqueredirect: If the redirect attribute of the fetch() request is set to manual, this response value will be returned.</li>\n</ul>\n<h4>Response.redirected</h4>\n<p>The Response.redirected property returns a Boolean value, indicating whether the request has been redirected.</p>\n<h4>Determine whether the request is successful</h4>\n<p>After fetch() sends a request, there is an important point to note: fetch() will report an error only when there’s a network error or cannot connect. In other cases, no error will be reported, but the request is considered successful.</p>\n<p>This means, even if the status code returned by the server is 4xx or 5xx, fetch() will not report an error (i.e. The Promise will not become rejected). Only by obtaining the true status code of the HTTP response through the Responese.status property, can it be determined whether the request is successful. Please see the following example:</p>\n<a href=\"https://medium.com/media/665e65d487ce15d48d08a73360f19b99/href\">https://medium.com/media/665e65d487ce15d48d08a73360f19b99/href</a><p>In the above example, the Responese.status attribute must be equal to 2xx (200~299) to determine that the request is successful. There’s no need to consider the URL jump (status code is 3xx) because fetch() will automatically convert the jumped status code to 200. Another method is to determine whether Responese.ok is true.</p>\n<a href=\"https://medium.com/media/e81b4e8fa9088f3bfb356dac5f80ea77/href\">https://medium.com/media/e81b4e8fa9088f3bfb356dac5f80ea77/href</a><h4>Response.headers property</h4>\n<p>The Response object also has a Responese.headers property, which points to a <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Headers\">Headers object</a>, which corresponds to all the headers of the HTTP response. Headers objects can be traversed using for...of loops.</p>\n<a href=\"https://medium.com/media/e78e37a3391dfc7694b5b8e11c2c428f/href\">https://medium.com/media/e78e37a3391dfc7694b5b8e11c2c428f/href</a><p>The Headers object provides the following methods to manipulate headers.</p>\n<ul>\n<li>Headers.get(): According to the specified key name, return the key-value.</li>\n<li>Headers.has(): Returns a Boolean value indicating whether a header is included.</li>\n<li>Headers.set(): Set the specified key name as the new key-value, if the key name does not exist, it will be added.</li>\n<li>Headers.append(): Add headers.</li>\n<li>Headers.delete(): Delete the header.</li>\n<li>Headers.keys(): Return an iterator that can traverse all the keys in turn.</li>\n<li>Headers.values(): Return an iterator that can traverse all key values in turn.</li>\n<li>Headers.entries(): Return an iterator that can traverse all key-value pairs in turn ([key, value]).</li>\n<li>Headers.forEach(): Traverse the headers, in turn. Each header will execute a parameter function.</li>\n</ul>\n<p>Some of the above methods can modify the headers because they inherit from the Headers interface. For HTTP responses, modifying headers is of little significance — many headers are read-only and browsers do not allow modification. Among these methods, the most commonly used is response.headers.get(), which is used to read the value of a certain header.</p>\n<a href=\"https://medium.com/media/ef94b7cae6d85c73cc1b764fde4f69f4/href\">https://medium.com/media/ef94b7cae6d85c73cc1b764fde4f69f4/href</a><p>The Headers.keys() and Headers.values() methods are used to traverse the header keys and key values respectively.</p>\n<a href=\"https://medium.com/media/1c7222d472b0be159f8237f941948f55/href\">https://medium.com/media/1c7222d472b0be159f8237f941948f55/href</a><p>The Headers.forEach() method can also traverse all key values and key names.</p>\n<a href=\"https://medium.com/media/e9d0906865cf98625d23be25b8da9cb6/href\">https://medium.com/media/e9d0906865cf98625d23be25b8da9cb6/href</a><h4>How to read content</h4>\n<p>The Response object provides different reading methods according to different types of data returned by the server.</p>\n<ul>\n<li>response.text(): Get the text string.</li>\n<li>response.json(): Get the JSON object.</li>\n<li>response.blob(): Get the binary Blob object.</li>\n<li>response.formData(): Get the FormData object.</li>\n<li>response.arrayBuffer(): Get the binary ArrayBuffer object.</li>\n</ul>\n<p>The above five reading methods are all asynchronous and all return Promise objects. You must wait until the end of the asynchronous operation to get the complete data returned by the server.</p>\n<h4>response.text()</h4>\n<p>response.text() can be used to get text data, such as HTML files.</p>\n<a href=\"https://medium.com/media/3d36dae5c1bf9e5f73f079962ba59365/href\">https://medium.com/media/3d36dae5c1bf9e5f73f079962ba59365/href</a><h4>response.json()</h4>\n<p>response.json() is mainly used to get the JSON data returned by the server. The example has been given earlier.</p>\n<h4>response.formData()</h4>\n<p>response.formData() is mainly used in Service Worker to intercept the form submitted by the user, modify some data, and then submit it to the server.</p>\n<h4>response.blob()</h4>\n<p>response.blob() is used to get the binary file.</p>\n<a href=\"https://medium.com/media/5e8b79479ae09fe490d9af8b18487364/href\">https://medium.com/media/5e8b79479ae09fe490d9af8b18487364/href</a><p>The above example reads the flower.jpg image file and displays it on the web page.</p>\n<h4>response.arrayBuffer()</h4>\n<p>response.arrayBuffer() is mainly used to obtain streaming media files.</p>\n<a href=\"https://medium.com/media/603beeb2cb1d0cf35de90e584395cd5f/href\">https://medium.com/media/603beeb2cb1d0cf35de90e584395cd5f/href</a><p>The above example is an example where response.arrayBuffer() gets the audio file song.ogg and then plays it online.</p>\n<h4>Response.clone()</h4>\n<p>The Stream object can only be read once and it is gone after reading. This means that only one of the five reading methods in the previous section can be used, otherwise, an error will be reported.</p>\n<pre>let text = await response.text();<br>let json = await response.json(); // Report an error</pre>\n<p>The above example uses response.text() first and then reads the Stream. After calling response.json() later, there’s no content to read, so an error is reported. The Response object provides the response.clone() method, which creates a copy of the Response object and implements multiple reads.</p>\n<a href=\"https://medium.com/media/e4053a76f78fd84a7cd033f1b5165780/href\">https://medium.com/media/e4053a76f78fd84a7cd033f1b5165780/href</a><p>In the above example, response.clone() made a copy of the Response object and then read the same image twice. The Response object also has a Response.redirect() method, which is used to redirect the Response result to the specified URL. This method is generally only used in Service Worker, so I won’t introduce it here.</p>\n<h4>Response.body attribute</h4>\n<p>The Response.body property is the underlying interface exposed by the Response object. It returns a ReadableStream object for user operations. It can be used to read content in blocks. One application is to display the progress of the download.</p>\n<a href=\"https://medium.com/media/9790f3efe764db5fcf0b8f081e5c97fc/href\">https://medium.com/media/9790f3efe764db5fcf0b8f081e5c97fc/href</a><p>In the above example, the response.body.getReader() method returns an iterator. The read() method of this traverser returns an object each time, representing the content block read this time. The done attribute of this object is a boolean value, used to judge whether it has been read. The value attribute is an arrayBuffer array, which represents the content of the content block. The value.length attribute is the size of the current block.</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/689/1*x8Is0ZGUft6UHAD2gB6izw.png\"><figcaption><a href=\"https://www.bccfalna.com/ebooks/wp-content/uploads/ebooks/2018/12/HTTP-Hyper-Text-Transfer-Protocol-for-Webpage-%E2%80%93-Request-and-Response-Core-JSP-in-Hindi.png\">https://www.bccfalna.com/ebooks/wp-content/uploads/ebooks/2018/12/HTTP-Hyper-Text-Transfer-Protocol-for-Webpage-%E2%80%93-Request-and-Response-Core-JSP-in-Hindi.png</a></figcaption></figure><h3>The Second Parameter of fetch(): Custom HTTP Request</h3>\n<p>The first parameter of fetch() is the URL, and the second parameter can also be accepted as a configuration object to customize the HTTP request sent out.</p>\n<pre>fetch(url, optionObj)</pre>\n<p>The optionObj of the above command is the second parameter. The HTTP request method, header, and data body are all set in this object. Here are some examples.</p>\n<h4>POST request</h4>\n<a href=\"https://medium.com/media/f5721cf8da6184fd42b09b7b2c93969b/href\">https://medium.com/media/f5721cf8da6184fd42b09b7b2c93969b/href</a><p>In the above example, the configuration object uses three attributes:</p>\n<ul>\n<li>method:The HTTP request method, POST, DELETE, PUT are all set in this property.</li>\n<li>headers:An object used to customize the header of the HTTP request.</li>\n<li>body:The data body of the POST request.</li>\n</ul>\n<p>Note that some headers cannot be set by the headers attribute, such as Content-Length, Cookie, Host, etc. They are automatically generated by the browser and cannot be modified.</p>\n<h4>Submit JSON data</h4>\n<a href=\"https://medium.com/media/34c1e41244bd546e313ad068a7b1da0d/href\">https://medium.com/media/34c1e41244bd546e313ad068a7b1da0d/href</a><p>In the above example, the header Content-Type should be set to 'application/json;charset=utf-8'. Because the default is to send plain text, the default value of Content-Type is 'text/plain;charset=UTF-8'.</p>\n<h4>Submit form</h4>\n<a href=\"https://medium.com/media/b245ad01ebefc2f8afc027743eb48b14/href\">https://medium.com/media/b245ad01ebefc2f8afc027743eb48b14/href</a><h4>File upload</h4>\n<p>If there is a file selector in the form, you can use the writing of the previous example. The uploaded file is included in the entire form and submitted together. Another method is to add files with scripts, construct a form, and upload, please see the example below.</p>\n<a href=\"https://medium.com/media/68a39a247c1f0f525bfb0b1fd3a17a79/href\">https://medium.com/media/68a39a247c1f0f525bfb0b1fd3a17a79/href</a><p>When uploading a binary file, there’s no need to modify the Content-Type of the header — the browser will automatically set it.</p>\n<h4>Upload binary data directly</h4>\n<p>fetch() can also upload binary data directly, putting Blob or arrayBuffer data in the body attribute.</p>\n<a href=\"https://medium.com/media/1b51a79c5a17d1dd95c4e02c377c81fd/href\">https://medium.com/media/1b51a79c5a17d1dd95c4e02c377c81fd/href</a><h3>The Complete Configuration Object of Fetch() API</h3>\n<p>The completion of the second parameter of fetch() API is as follows:</p>\n<a href=\"https://medium.com/media/f425f83c3bab22560cde7e0b67be6810/href\">https://medium.com/media/f425f83c3bab22560cde7e0b67be6810/href</a><p>The bottom layer of the fetch() request uses the interface of the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Request/Request\">Request() object</a>. The parameters are exactly the same, so the above API is also the API of Request(). Among these attributes, headers, body, and method have been given examples before. The following is an introduction to other attributes.</p>\n<h4><strong>cache</strong></h4>\n<p>The cache attribute specifies how to handle the cache. The possible values are as follows:</p>\n<ul>\n<li>default:The default value is to find matching requests in the cache first.</li>\n<li>no-store:Request the remote server directly and do not update the cache.</li>\n<li>reload:Directly request the remote server and update the cache.</li>\n<li>no-cache:Compare the server resources with the local cache and use the server resources when there is a new version. Otherwise use the local cache.</li>\n<li>force-cache:Cache is the priority, and the remote server is only requested if there is no cache.</li>\n<li>only-if-cached:Only check the cache. If the cache does not exist, a 504 error will be returned.</li>\n</ul>\n<h4><strong>mode</strong></h4>\n<p>The mode attribute specifies the requested mode. The possible values are as follows:</p>\n<ul>\n<li>cors:The default value allows cross-domain requests.</li>\n<li>same-origin:Only same-origin requests are allowed.</li>\n<li>no-cors:The request method is limited to GET, POST and HEAD, and only a limited number of simple headers can be used, and cross-domain complex headers cannot be added, which is equivalent to the request that can be made by submitting the form.</li>\n</ul>\n<h4><strong>credentials</strong></h4>\n<p>The credentials attribute specifies whether to send cookies. The possible values are as follows:</p>\n<ul>\n<li>same-origin:By default, cookies are sent when requesting from the same origin, but not when requesting across domains.</li>\n<li>include:Regardless of same-origin requests or cross-domain requests, cookies are always sent.</li>\n<li>omit:Never send.</li>\n</ul>\n<p>For cross-domain requests to send cookies, the credentials attribute needs to be set to include.</p>\n<a href=\"https://medium.com/media/bffb2739ff4353cc61e58c7e7a321923/href\">https://medium.com/media/bffb2739ff4353cc61e58c7e7a321923/href</a><h4><strong>signal</strong></h4>\n<p>The signal attribute specifies an AbortSignal instance to cancel the fetch() request, see the next section for details.</p>\n<h4><strong>keepalive</strong></h4>\n<p>The keepalive attribute is used when the page is uninstalled to tell the browser to keep the connection in the background and continue to send data. A typical scenario is that when the user leaves the web page, the script submits some statistical information about the user’s behavior to the server. At this time, if the keepalive attribute is not used, the data may not be sent because the browser has uninstalled the page.</p>\n<a href=\"https://medium.com/media/9dffdfaa0bbe3c344cb5dc736f76751e/href\">https://medium.com/media/9dffdfaa0bbe3c344cb5dc736f76751e/href</a><h4><strong>redirect</strong></h4>\n<p>The redirect attribute specifies the processing method for HTTP redirects. The possible values are as follows:</p>\n<ul>\n<li>follow:By default, fetch() follows HTTP redirects.</li>\n<li>error:If a jump occurs, fetch() will report an error.</li>\n<li>manual:fetch() does not follow the HTTP redirection, but the response.url property will point to the new URL, and the response.redirected property will become true. The developer decides how to handle the redirection later.</li>\n</ul>\n<h4><strong>integrity</strong></h4>\n<p>The integrity attribute specifies a hash value to check whether the data returned by the HTTP response is equal to the preset hash value. For example, when downloading a file, check whether the SHA-256 hash value of the file matches to ensure that it has not been tampered with.</p>\n<a href=\"https://medium.com/media/c6f188005cff10daec2765764a53a2e9/href\">https://medium.com/media/c6f188005cff10daec2765764a53a2e9/href</a><h4><strong>referrer</strong></h4>\n<p>The referrer attribute is used to set the referrer header of the fetch() request. This attribute can be any string or an empty string (that is, no referrer header is sent).</p>\n<a href=\"https://medium.com/media/3740312ff7331a2dbc11faa017ad4f29/href\">https://medium.com/media/3740312ff7331a2dbc11faa017ad4f29/href</a><h4><strong>referrerPolicy</strong></h4>\n<p>The referrerPolicy attribute is used to set the rules of the Referrer header. The possible values are as follows:</p>\n<ul>\n<li>no-referrer-when-downgrade:The default value, the Referrer header is always sent, unless it is not sent when requesting HTTP resources from an HTTPS page.</li>\n<li>no-referrer:The Referrer header is not sent.</li>\n<li>origin:The Referrer header only contains the domain name, not the complete path.</li>\n<li>origin-when-cross-origin:The Referrer header of the same-origin request contains the complete path, and the cross-domain request only contains the domain name.</li>\n<li>same-origin:Cross-domain requests do not send Referrer, but same-source requests are sent.</li>\n<li>strict-origin:The Referrer header only contains the domain name. The Referrer header is not sent when the HTTPS page requests HTTP resources.</li>\n<li>strict-origin-when-cross-origin:The Referrer header contains the full path for the same-origin request, and only the domain name for the cross-domain request. This header is not sent when the HTTPS page requests HTTP resources.</li>\n<li>unsafe-url: No matter what the situation, always send the Referrer header.</li>\n</ul>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*8ELG0a7FoW2yu_UyRaTWrg.jpeg\"><figcaption>Photo by <a href=\"https://unsplash.com/@sigmund?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Sigmund</a> on <a href=\"https://unsplash.com/s/photos/complete-configuration?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Unsplash</a></figcaption></figure><h3>Cancel fetch() Request</h3>\n<p>After the fetch() request is sent, if you want to cancel halfway, you need to use the AbortController object:</p>\n<a href=\"https://medium.com/media/521a9ef7287385a7cef496fe50dcb562/href\">https://medium.com/media/521a9ef7287385a7cef496fe50dcb562/href</a><p>In the above example, first create an AbortController instance, then send a fetch() request. The signal property of the configuration object must specify that it receives the signal Controller.signal sent by the AbortController instance. The Controller.abort method is used to signal the cancellation. At this time, the abort event will be triggered. This event can be monitored, or you can determine whether the cancel signal has been sent through the Controller.signal.aborted property. The following is an example of automatically canceling the request after one second:</p>\n<a href=\"https://medium.com/media/7d789ec5bd43ae3b4d084a370d5db8a7/href\">https://medium.com/media/7d789ec5bd43ae3b4d084a370d5db8a7/href</a><figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*CSK0GdPArv3m1UFDLNJT1w.jpeg\"><figcaption>Photo by <a href=\"https://unsplash.com/@instagramfotografin?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Peggy Anke</a> on <a href=\"https://unsplash.com/s/photos/cancel-request?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Unsplash</a></figcaption></figure><h3>Conclusion</h3>\n<p>Here I described Fetch API usages, handle HTTP response, custom HTTP request, configuration object, and cancel requests in JavaScript. The Fetch API can be a bit overwhelming, but it’s absolutely vital as you continue to learn code in JavaScript.</p>\n<p>Happy coding!</p>\n<img src=\"https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8e8203c0965\" width=\"1\" height=\"1\" alt=\"\"><hr>\n<p><a href=\"https://betterprogramming.pub/deep-insights-into-javascripts-fetch-api-e8e8203c0965\">Deep Insights Into JavaScript’s Fetch API</a> was originally published in <a href=\"https://betterprogramming.pub/\">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>\n",
"enclosure": {},
"categories": [
"javascript",
"programming",
"software-development",
"api",
"web-development"
],
"clapCount": 371,
"voterCount": 44,
"responseCount": 0,
"readingTime": 11
},
{
"title": "Easy to Learn React Hooks",
"pubDate": "2020-12-31 09:30:05",
"link": "https://medium.datadriveninvestor.com/easy-to-learn-react-hooks-7db7763608f5?source=rss-b255948cc1f5------2",
"guid": "https://medium.com/p/7db7763608f5",
"author": "Sabesan Sathananthan",
"thumbnail": "https://cdn-images-1.medium.com/max/1024/1*fbPkB4GcfdqPbQ9k3Wv6MQ.jpeg",
"description": "\n<h4>FRONT END</h4>\n<h4>Take useEffect() as an example</h4>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*fbPkB4GcfdqPbQ9k3Wv6MQ.jpeg\"><figcaption>Photo by <a href=\"https://unsplash.com/@blizzard88?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Grant Durr</a> on <a href=\"https://unsplash.com/s/photos/hook?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Unsplash</a></figcaption></figure><p>I already wrote about <a href=\"https://towardsdatascience.com/react-best-practices-804def6d5215\">React best practices</a>. I have mentioned that React hooks write stateful functional components. Nowadays, Most of the React frameworks such as react-i18next, Material-UI, and etc are encouraged to use React hooks. However, recently I have come to realize that React hooks are very useful. React hooks are introduced after the React v16.08. Here I am going to describe React hooks very simply and easily. This is my 34th Medium article.</p>\n<h3>Two sets of React API</h3>\n<p>In the past, there was only one set of React API, now there are two sets: class API and function-based hooks API. Any component can be written by a class or a hook. Here is how to write the class.</p>\n<a href=\"https://medium.com/media/93a1e72f5c35acedabb55b638d41a515/href\">https://medium.com/media/93a1e72f5c35acedabb55b638d41a515/href</a><p>Let’s look at the way the hook is written, that is, the function.</p>\n<a href=\"https://medium.com/media/6aacb985b2907ef141050f2eebd30d6b/href\">https://medium.com/media/6aacb985b2907ef141050f2eebd30d6b/href</a><p>These two ways of writing have exactly the same effect. Beginners will naturally ask: “Which API should I use?”</p>\n<p>The <a href=\"https://reactjs.org/docs/hooks-faq.html#should-i-use-hooks-classes-or-a-mix-of-both\">official recommendation</a> is to use hooks (functions) instead of classes. Because hooks are more concise and less code, they are “lighter” to use, while classes are “heavier”. Moreover, hooks are functions, which are more in line with the functional nature of React.</p>\n<p>The following is a comparison of the amount of code for class components (left) and functional components (right). For complex components, the difference is even more.</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*fyHQ5LZieX8UbpZU4zMhgQ.jpeg\"></figure><p>However, the flexibility of hooks is too great for beginners to understand. Many people have little knowledge and can easily write messy and unmaintainable code. It would be better to use classes. Because classes have many mandatory grammatical constraints, it is not easy to mess up.</p>\n<h3>The difference between classes and functions</h3>\n<p>Strictly speaking, there is a difference between class components and functional components. Different writing methods represent different programming methodologies.</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/529/1*TVhzFkIjNtmpOYt7xiR-DQ.jpeg\"></figure><p><strong>A class is an encapsulation of data and logic. </strong>In other words, the state and operation method of the component are encapsulated together. If you choose the type of writing, you should write related data and operations in the same class.</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1021/1*yBmNd02dBwKNbGIcwKgYgg.png\"><figcaption><a href=\"https://upload.wikimedia.org/wikipedia/commons/thumb/3/3b/Function_machine2.svg/1200px-Function_machine2.svg.png\">https://upload.wikimedia.org/wikipedia/commons/thumb/3/3b/Function_machine2.svg/1200px-Function_machine2.svg.png</a></figcaption></figure><p><strong>Generally speaking, functions should only do one thing, which is to return a value. </strong>If you have multiple operations, each operation should be written as a separate function. Moreover, the state of the data should be separated from the operation method. According to this philosophy, React’s functional components should only do one thing: return the HTML code of the component, and have no other functions.</p>\n<p>Take the below functional component as an example.</p>\n<a href=\"https://medium.com/media/6aacb985b2907ef141050f2eebd30d6b/href\">https://medium.com/media/6aacb985b2907ef141050f2eebd30d6b/href</a><p>This function only does one thing, which is to return the HTML code of the component based on the input parameters. This kind of function that only performs simple data calculation (conversion) is called <strong>“pure function”</strong> in functional programming.</p>\n<h3>What are the side effects?</h3>\n<p>Seeing this, you may have a question: If pure functions can only perform data calculations, where should those operations that do not involve calculations (such as generating logs, storing data, changing application status, etc.) be written?</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/550/1*-YvOvw7xuTF5oA30YEwQUw.jpeg\"><figcaption><a href=\"https://functionalprogrammingcsharp.com/images/posts/pure-functions.jpg\">https://functionalprogrammingcsharp.com/images/posts/pure-functions.jpg</a></figcaption></figure><p>Functional programming that calculates those operations without relating to data are called “secondary effects” <strong>(Side Effect)</strong>. If a function directly contains operations that produce side effects, it is no longer a pure function, and we call it an impure function.</p>\n<p>Only through indirect means (that is, through other function calls) inside a pure function can it contain side effects.</p>\n<h3>The role of hooks</h3>\n<p>After talking for a long time, what exactly is a hook? In a word, <strong>the hook is the side effect solution of the React functional component, which is used to introduce side effects to the functional component. </strong>The body of the function component should only be used to return the HTML code of the component, and all other operations (side effects) must be introduced through hooks.</p>\n<p>Since there are so many side effects, there are many kinds of hooks. React provides special hooks for many common operations (side effects).</p>\n<ul>\n<li>useState(): Save state</li>\n<li>useContext(): Save context</li>\n<li>useRef(): Save reference</li>\n<li>…</li>\n</ul>\n<p>These hooks above, are the introduction of a specific side effect and useEffect()<strong> is a common side effect of the hook</strong>. You can use it when you can't find the corresponding hook. In fact, as you can see from the name, it is directly related to side effects.</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1000/1*lXbyzFjWcBEmiCEzdZ9DDQ.jpeg\"><figcaption><a href=\"https://dev.to/swapnadeepmohapatra/useeffect-react-hooks-25fb\">https://dev.to/swapnadeepmohapatra/useeffect-react-hooks-25fb</a></figcaption></figure><h3>The usage of useEffect()</h3>\n<p>useEffect() is a function itself, provided by the React framework, and can be called inside the functional component.</p>\n<p>For example, we hope that after the component is loaded, the page title (document.title) will change accordingly. Then, the operation of changing the title of the webpage is a side effect of the component, which useEffect() implemented.</p>\n<a href=\"https://medium.com/media/1f5c3e05b455b8992ee4a2f496b94345/href\">https://medium.com/media/1f5c3e05b455b8992ee4a2f496b94345/href</a><p>In the above example, useEffect() the parameter is a function, which is the side effect to be completed (change the page title). After the component is loaded, React will execute this function.</p>\n<a href=\"https://medium.com/media/118ea38496e73971eefc32b186ca8bff/href\">https://medium.com/media/118ea38496e73971eefc32b186ca8bff/href</a><p>The role of useEffect() is to specify a side effect function, which is automatically executed every time the component is rendered. After the component is first loaded in the web page DOM, the side effect function will also be executed.</p>\n<h3>The second parameter of useEffect()</h3>\n<p>Sometimes, we don’t want useEffect() to execute every rendering. At this time, we can use its second parameter to use an array to specify the dependencies of the side effect function. Only when the dependencies change, the rendering will be performed again.</p>\n<a href=\"https://medium.com/media/8575516111930a6bbd3dc9b3869bf8c9/href\">https://medium.com/media/8575516111930a6bbd3dc9b3869bf8c9/href</a><p>In the above example, useEffect() the second parameter is an array that specifies the dependency (props.name) of the first parameter (side effect function ). Only when the variable changes, the side effect function will be executed.</p>\n<p>If the second parameter is an empty array, it means that the side effect parameter does not have any dependencies. Therefore, the side effect function will only be executed once after the component is loaded into the DOM, and the subsequent component will be re-rendered and will not be executed again. This is reasonable because the side effects do not depend on any variables, so no matter how those variables change, the execution result of the side effect function will not change, so it is enough to run it once.</p>\n<h3>The purpose of useEffect()</h3>\n<p>As long as it is a side effect, you can use the useEffect() introduction. Its common uses are as follows.</p>\n<ul>\n<li>Data fetching</li>\n<li>Event monitoring or subscription (setting up a subscription)</li>\n<li>Change the DOM (changing the DOM)</li>\n<li>Output log (logging)</li>\n</ul>\n<p>The following is an example of getting data from a remote server.</p>\n<a href=\"https://medium.com/media/967993352682d5bcf73d6a1b2f236e44/href\">https://medium.com/media/967993352682d5bcf73d6a1b2f236e44/href</a><a href=\"https://medium.com/media/ab53f7870d31861185bad60a0ff808ce/href\">https://medium.com/media/ab53f7870d31861185bad60a0ff808ce/href</a><p>In the above example, it is useState()used to generate a state variable ( data) to save the acquired data; useEffect()inside the side effect function, there is an async function to asynchronously acquire data from the server. After getting the data, use the setData()trigger component to re-render.</p>\n<p>Since data acquisition only needs to be executed once, useEffect()the second parameter of the above example is an empty array.</p>\n<h3>The return value of useEffect()</h3>\n<p>Side effects occur as components are loaded, so when components are unloaded, these side effects may need to be cleaned up.</p>\n<p>useEffect() allows to return a function, which is executed when the component is unloaded to clean up side effects. If you don't need to clean up the side effects of useEffect() you don't need to return any value.</p>\n<pre>useEffect(() => {<br> const subscription = props.source.subscribe();<br><em>return</em> () => {<br> subscription.unsubscribe();<br> };<br>}, [props.source]);</pre>\n<p>In the above example, useEffect() an event is subscribed when the component is loaded, and a cleanup function is returned, and the subscription is canceled when the component is unloaded.</p>\n<p>In actual use, since the side effect function executes every rendering by default, the cleaning function will not only be executed once when the component is unloaded but also once before the side effect function is re-executed to clean up the side effects of the previous rendering effect.</p>\n<h3>useEffect() attention points</h3>\n<p>There is one thing to pay attention to when using useEffect(). If there are multiple side effects, multiple useEffect() should be called instead of being combined and written together.</p>\n<a href=\"https://medium.com/media/4a81faee00d203eedc6cf5d47521d2bc/href\">https://medium.com/media/4a81faee00d203eedc6cf5d47521d2bc/href</a><p>The above example is wrong. There are two timers in the side effect function. They are not related. In fact, they are two unrelated side effects and should not be written together. The correct way is to write them separately into two useEffect().</p>\n<a href=\"https://medium.com/media/6508ee90fea696cbc4b9eb57eb811e82/href\">https://medium.com/media/6508ee90fea696cbc4b9eb57eb811e82/href</a><h3>Conclusion</h3>\n<p>Most of my social media friends suggest to me to write about React hooks because they want to understand them easily. Here I have written about the hooks with basic Javascript concepts and took the useEffect() as an example.</p>\n<p>Happy New Year 🎉</p>\n<p>Happy coding 😎</p>\n<p><strong>Gain Access to Expert View — </strong><a href=\"https://datadriveninvestor.com/ddi-intel\"><strong>Subscribe to DDI Intel</strong></a></p>\n<img src=\"https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7db7763608f5\" width=\"1\" height=\"1\" alt=\"\"><hr>\n<p><a href=\"https://medium.datadriveninvestor.com/easy-to-learn-react-hooks-7db7763608f5\">Easy to Learn React Hooks</a> was originally published in <a href=\"https://medium.datadriveninvestor.com/\">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>\n",
"content": "\n<h4>FRONT END</h4>\n<h4>Take useEffect() as an example</h4>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*fbPkB4GcfdqPbQ9k3Wv6MQ.jpeg\"><figcaption>Photo by <a href=\"https://unsplash.com/@blizzard88?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Grant Durr</a> on <a href=\"https://unsplash.com/s/photos/hook?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Unsplash</a></figcaption></figure><p>I already wrote about <a href=\"https://towardsdatascience.com/react-best-practices-804def6d5215\">React best practices</a>. I have mentioned that React hooks write stateful functional components. Nowadays, Most of the React frameworks such as react-i18next, Material-UI, and etc are encouraged to use React hooks. However, recently I have come to realize that React hooks are very useful. React hooks are introduced after the React v16.08. Here I am going to describe React hooks very simply and easily. This is my 34th Medium article.</p>\n<h3>Two sets of React API</h3>\n<p>In the past, there was only one set of React API, now there are two sets: class API and function-based hooks API. Any component can be written by a class or a hook. Here is how to write the class.</p>\n<a href=\"https://medium.com/media/93a1e72f5c35acedabb55b638d41a515/href\">https://medium.com/media/93a1e72f5c35acedabb55b638d41a515/href</a><p>Let’s look at the way the hook is written, that is, the function.</p>\n<a href=\"https://medium.com/media/6aacb985b2907ef141050f2eebd30d6b/href\">https://medium.com/media/6aacb985b2907ef141050f2eebd30d6b/href</a><p>These two ways of writing have exactly the same effect. Beginners will naturally ask: “Which API should I use?”</p>\n<p>The <a href=\"https://reactjs.org/docs/hooks-faq.html#should-i-use-hooks-classes-or-a-mix-of-both\">official recommendation</a> is to use hooks (functions) instead of classes. Because hooks are more concise and less code, they are “lighter” to use, while classes are “heavier”. Moreover, hooks are functions, which are more in line with the functional nature of React.</p>\n<p>The following is a comparison of the amount of code for class components (left) and functional components (right). For complex components, the difference is even more.</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*fyHQ5LZieX8UbpZU4zMhgQ.jpeg\"></figure><p>However, the flexibility of hooks is too great for beginners to understand. Many people have little knowledge and can easily write messy and unmaintainable code. It would be better to use classes. Because classes have many mandatory grammatical constraints, it is not easy to mess up.</p>\n<h3>The difference between classes and functions</h3>\n<p>Strictly speaking, there is a difference between class components and functional components. Different writing methods represent different programming methodologies.</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/529/1*TVhzFkIjNtmpOYt7xiR-DQ.jpeg\"></figure><p><strong>A class is an encapsulation of data and logic. </strong>In other words, the state and operation method of the component are encapsulated together. If you choose the type of writing, you should write related data and operations in the same class.</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1021/1*yBmNd02dBwKNbGIcwKgYgg.png\"><figcaption><a href=\"https://upload.wikimedia.org/wikipedia/commons/thumb/3/3b/Function_machine2.svg/1200px-Function_machine2.svg.png\">https://upload.wikimedia.org/wikipedia/commons/thumb/3/3b/Function_machine2.svg/1200px-Function_machine2.svg.png</a></figcaption></figure><p><strong>Generally speaking, functions should only do one thing, which is to return a value. </strong>If you have multiple operations, each operation should be written as a separate function. Moreover, the state of the data should be separated from the operation method. According to this philosophy, React’s functional components should only do one thing: return the HTML code of the component, and have no other functions.</p>\n<p>Take the below functional component as an example.</p>\n<a href=\"https://medium.com/media/6aacb985b2907ef141050f2eebd30d6b/href\">https://medium.com/media/6aacb985b2907ef141050f2eebd30d6b/href</a><p>This function only does one thing, which is to return the HTML code of the component based on the input parameters. This kind of function that only performs simple data calculation (conversion) is called <strong>“pure function”</strong> in functional programming.</p>\n<h3>What are the side effects?</h3>\n<p>Seeing this, you may have a question: If pure functions can only perform data calculations, where should those operations that do not involve calculations (such as generating logs, storing data, changing application status, etc.) be written?</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/550/1*-YvOvw7xuTF5oA30YEwQUw.jpeg\"><figcaption><a href=\"https://functionalprogrammingcsharp.com/images/posts/pure-functions.jpg\">https://functionalprogrammingcsharp.com/images/posts/pure-functions.jpg</a></figcaption></figure><p>Functional programming that calculates those operations without relating to data are called “secondary effects” <strong>(Side Effect)</strong>. If a function directly contains operations that produce side effects, it is no longer a pure function, and we call it an impure function.</p>\n<p>Only through indirect means (that is, through other function calls) inside a pure function can it contain side effects.</p>\n<h3>The role of hooks</h3>\n<p>After talking for a long time, what exactly is a hook? In a word, <strong>the hook is the side effect solution of the React functional component, which is used to introduce side effects to the functional component. </strong>The body of the function component should only be used to return the HTML code of the component, and all other operations (side effects) must be introduced through hooks.</p>\n<p>Since there are so many side effects, there are many kinds of hooks. React provides special hooks for many common operations (side effects).</p>\n<ul>\n<li>useState(): Save state</li>\n<li>useContext(): Save context</li>\n<li>useRef(): Save reference</li>\n<li>…</li>\n</ul>\n<p>These hooks above, are the introduction of a specific side effect and useEffect()<strong> is a common side effect of the hook</strong>. You can use it when you can't find the corresponding hook. In fact, as you can see from the name, it is directly related to side effects.</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1000/1*lXbyzFjWcBEmiCEzdZ9DDQ.jpeg\"><figcaption><a href=\"https://dev.to/swapnadeepmohapatra/useeffect-react-hooks-25fb\">https://dev.to/swapnadeepmohapatra/useeffect-react-hooks-25fb</a></figcaption></figure><h3>The usage of useEffect()</h3>\n<p>useEffect() is a function itself, provided by the React framework, and can be called inside the functional component.</p>\n<p>For example, we hope that after the component is loaded, the page title (document.title) will change accordingly. Then, the operation of changing the title of the webpage is a side effect of the component, which useEffect() implemented.</p>\n<a href=\"https://medium.com/media/1f5c3e05b455b8992ee4a2f496b94345/href\">https://medium.com/media/1f5c3e05b455b8992ee4a2f496b94345/href</a><p>In the above example, useEffect() the parameter is a function, which is the side effect to be completed (change the page title). After the component is loaded, React will execute this function.</p>\n<a href=\"https://medium.com/media/118ea38496e73971eefc32b186ca8bff/href\">https://medium.com/media/118ea38496e73971eefc32b186ca8bff/href</a><p>The role of useEffect() is to specify a side effect function, which is automatically executed every time the component is rendered. After the component is first loaded in the web page DOM, the side effect function will also be executed.</p>\n<h3>The second parameter of useEffect()</h3>\n<p>Sometimes, we don’t want useEffect() to execute every rendering. At this time, we can use its second parameter to use an array to specify the dependencies of the side effect function. Only when the dependencies change, the rendering will be performed again.</p>\n<a href=\"https://medium.com/media/8575516111930a6bbd3dc9b3869bf8c9/href\">https://medium.com/media/8575516111930a6bbd3dc9b3869bf8c9/href</a><p>In the above example, useEffect() the second parameter is an array that specifies the dependency (props.name) of the first parameter (side effect function ). Only when the variable changes, the side effect function will be executed.</p>\n<p>If the second parameter is an empty array, it means that the side effect parameter does not have any dependencies. Therefore, the side effect function will only be executed once after the component is loaded into the DOM, and the subsequent component will be re-rendered and will not be executed again. This is reasonable because the side effects do not depend on any variables, so no matter how those variables change, the execution result of the side effect function will not change, so it is enough to run it once.</p>\n<h3>The purpose of useEffect()</h3>\n<p>As long as it is a side effect, you can use the useEffect() introduction. Its common uses are as follows.</p>\n<ul>\n<li>Data fetching</li>\n<li>Event monitoring or subscription (setting up a subscription)</li>\n<li>Change the DOM (changing the DOM)</li>\n<li>Output log (logging)</li>\n</ul>\n<p>The following is an example of getting data from a remote server.</p>\n<a href=\"https://medium.com/media/967993352682d5bcf73d6a1b2f236e44/href\">https://medium.com/media/967993352682d5bcf73d6a1b2f236e44/href</a><a href=\"https://medium.com/media/ab53f7870d31861185bad60a0ff808ce/href\">https://medium.com/media/ab53f7870d31861185bad60a0ff808ce/href</a><p>In the above example, it is useState()used to generate a state variable ( data) to save the acquired data; useEffect()inside the side effect function, there is an async function to asynchronously acquire data from the server. After getting the data, use the setData()trigger component to re-render.</p>\n<p>Since data acquisition only needs to be executed once, useEffect()the second parameter of the above example is an empty array.</p>\n<h3>The return value of useEffect()</h3>\n<p>Side effects occur as components are loaded, so when components are unloaded, these side effects may need to be cleaned up.</p>\n<p>useEffect() allows to return a function, which is executed when the component is unloaded to clean up side effects. If you don't need to clean up the side effects of useEffect() you don't need to return any value.</p>\n<pre>useEffect(() => {<br> const subscription = props.source.subscribe();<br><em>return</em> () => {<br> subscription.unsubscribe();<br> };<br>}, [props.source]);</pre>\n<p>In the above example, useEffect() an event is subscribed when the component is loaded, and a cleanup function is returned, and the subscription is canceled when the component is unloaded.</p>\n<p>In actual use, since the side effect function executes every rendering by default, the cleaning function will not only be executed once when the component is unloaded but also once before the side effect function is re-executed to clean up the side effects of the previous rendering effect.</p>\n<h3>useEffect() attention points</h3>\n<p>There is one thing to pay attention to when using useEffect(). If there are multiple side effects, multiple useEffect() should be called instead of being combined and written together.</p>\n<a href=\"https://medium.com/media/4a81faee00d203eedc6cf5d47521d2bc/href\">https://medium.com/media/4a81faee00d203eedc6cf5d47521d2bc/href</a><p>The above example is wrong. There are two timers in the side effect function. They are not related. In fact, they are two unrelated side effects and should not be written together. The correct way is to write them separately into two useEffect().</p>\n<a href=\"https://medium.com/media/6508ee90fea696cbc4b9eb57eb811e82/href\">https://medium.com/media/6508ee90fea696cbc4b9eb57eb811e82/href</a><h3>Conclusion</h3>\n<p>Most of my social media friends suggest to me to write about React hooks because they want to understand them easily. Here I have written about the hooks with basic Javascript concepts and took the useEffect() as an example.</p>\n<p>Happy New Year 🎉</p>\n<p>Happy coding 😎</p>\n<p><strong>Gain Access to Expert View — </strong><a href=\"https://datadriveninvestor.com/ddi-intel\"><strong>Subscribe to DDI Intel</strong></a></p>\n<img src=\"https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7db7763608f5\" width=\"1\" height=\"1\" alt=\"\"><hr>\n<p><a href=\"https://medium.datadriveninvestor.com/easy-to-learn-react-hooks-7db7763608f5\">Easy to Learn React Hooks</a> was originally published in <a href=\"https://medium.datadriveninvestor.com/\">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>\n",
"enclosure": {},
"categories": [
"javascript",
"functional-programming",
"web-development",
"react",
"front-end-development"
],
"clapCount": 244,
"voterCount": 10,
"responseCount": 0,
"readingTime": 6
},
{
"title": "Embed your GitHub project on your React website",
"pubDate": "2020-10-05 20:10:01",
"link": "https://bootcamp.uxdesign.cc/embed-your-github-project-on-your-react-website-ccefacc30f62?source=rss-b255948cc1f5------2",
"guid": "https://medium.com/p/ccefacc30f62",
"author": "Sabesan Sathananthan",
"thumbnail": "https://cdn-images-1.medium.com/max/1024/1*2hWfwgI2WwfkkD4QNdUpbQ.jpeg",
"description": "\n<h4>FRONT END</h4>\n<h4>Embed GitHub repo on your Website using Material-UI gives better UI</h4>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*2hWfwgI2WwfkkD4QNdUpbQ.jpeg\"><figcaption>Photo by <a href=\"https://unsplash.com/@markuswinkler?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Markus Winkler</a> on <a href=\"https://unsplash.com/s/photos/github?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Unsplash</a></figcaption></figure><blockquote>They say imitation is a form of flattery but honey, it is time to get your own ideas.</blockquote>\n<p>I thought to embed my GitHub projects on my <a href=\"https://sabesansathananthan.now.sh/\">website</a> like pinned repositories in GitHub. First I faced a problem that how could I get the programming language colors as shown in GitHub. Then I found that was defined in GitHub <a href=\"https://raw.githubusercontent.com/github/linguist/master/lib/linguist/languages.yml\">linguist</a>. But linguist file defined in YAML Therefore, I fetched that data and convert it to JSON. Therefore I created an API to fetch the linguist details. But In this article, I am not going to talk about that. If you want to watch the API repository click the <a href=\"https://github.com/sabesansathananthan/github-linguist-json\">link</a>. Here I will describe how I created the GitHub repository cards in React application. This is my 33rd Medium article.</p>\n<p>In this article, I am going to say how to start from scratch. Here you could see the live <a href=\"https://react-github-repo-cards.vercel.app/\">demo</a> of this react application. Now I finished this project and have a repo in GitHub.</p>\n<h3>Step1: Setup Project</h3>\n<p>First, you need to create a react application. For that run the following command in your shell/terminal in a specific folder (e.g., desktop )</p>\n<pre>npx create-react-app github-repo</pre>\n<p>A new folder will be created, and it will be named as a github-repo. From this step, our application is bootstrapped with <a href=\"https://github.com/facebook/create-react-app\">Create React App</a>. For more information, click the <a href=\"https://github.com/facebook/create-react-app\">link</a>. Then open that project in your IDE. I am personally using the VS Code IDE. You need to delete some files and organize the files for the development after you open the folder in your IDE. Therefore you need to go to the src folder and delete Logo.svg, App.css, index.css, and App.test.js files. And create the following folders inside the src folder named components and api.</p>\n<p>Now open the index.js file and delete the following snippet in index.js file.</p>\n<pre><em>import</em> ‘./index.css’;</pre>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*lxNhDY0lI5CcPIK8Wp4Owg.jpeg\"><figcaption>Photo by <a href=\"https://www.pexels.com/@dhayaeddart?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels\">Dhaya Eddine Bentaleb</a> from <a href=\"https://www.pexels.com/photo/wood-fashion-sunglasses-art-4935600/?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels\">Pexels</a></figcaption></figure><h3>Step 2: Install packages</h3>\n<p>Install Material-UI for Material Design form component.</p>\n<pre>npm install @material-ui/core --save</pre>\n<p>Install Axios to make HTTP requests to the API.</p>\n<pre>npm install axios --save</pre>\n<blockquote>\n<em>Note: Fetching JSON Data can be achieved through the fetch API in JavaScript. Reason for using Axios Even old browsers like IE11 can run Axios without any issue. </em><em>Fetch(), on the other hand, only supports Chrome 42+, Firefox 39+, Edge 14+, and Safari 10.1+ (you can see the full compatibly table on </em><a href=\"https://caniuse.com/#search=Fetch\"><em>Can I use</em></a><em>…)</em>\n</blockquote>\n<p>Open the index.html file in the public folder and paste the below code inside the <head> </head> tag.</p>\n<pre><link <em>rel</em>=”stylesheet” <em>href</em>=”https://cdnjs.cloudflare.com/ajax/libs/octicons/3.5.0/octicons.min.css\" /></pre>\n<p>the above process is not installing the package. You are going to use octionsCDN.</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*LCfjLo6fyEJisPOr4uNMgA.jpeg\"><figcaption>Photo by <a href=\"https://www.pexels.com/@cottonbro?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels\">cottonbro</a> from <a href=\"https://www.pexels.com/photo/woman-using-a-computer-5473298/?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels\">Pexels</a></figcaption></figure><h3>Step 3: Implementation</h3>\n<p>First thing first you need to go to GitHub and then go to the settings. Click the Developer Settings in the left column. Click the personal access token and generate a new token and copy that token. open your react project and create a new file in the root folder named .env. Inside the .env file add the following code. Replace your copied GitHub Personal Access Token instead of <em>Your_Personal_Access_Token .</em></p>\n<pre>REACT_APP_API_KEY = Your_Personal_Access_Token</pre>\n<p>Inside the api folder create a new file named Github.js. Add the following code in the Github.js file.</p>\n<a href=\"https://medium.com/media/80e2ea0abdf8baa91bda9b6cc2301bf8/href\">https://medium.com/media/80e2ea0abdf8baa91bda9b6cc2301bf8/href</a><p>Replace your GitHub user name instead of <em>sabesansathananthan</em> on line 2.</p>\n<p>Inside the components folder, create a new file named GitHubCards.js. Add the following code in the GitHubCards.js file.</p>\n<a href=\"https://medium.com/media/4d450a719f69aeb6a6601bcb0d0ec2bd/href\">https://medium.com/media/4d450a719f69aeb6a6601bcb0d0ec2bd/href</a><p>In line 28, You are fetching the linguist API using Axios and then you set your language state. Form line 31 to line 42, You are fetching GitHub API for each repository. From line 46 to 52, You are sorting repo array elements according to the stargazers_count (stars count).</p>\n<p>Inside the components folder, create a new file named RepoCard.js. Add the following code in the RepoCard.js file.</p>\n<a href=\"https://medium.com/media/8ab5dacde0fe37796ccd1c7848de3e03/href\">https://medium.com/media/8ab5dacde0fe37796ccd1c7848de3e03/href</a><p>The above functional component returns JSX elements and Material-UI components.</p>\n<p>Finally, Render the GitHubCards component in App.js, as shown below.</p>\n<a href=\"https://medium.com/media/3948aebd1ff6d2753e9994bc0aeca4d7/href\">https://medium.com/media/3948aebd1ff6d2753e9994bc0aeca4d7/href</a><figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*gD2Ef2dVWMHWA39cP3DJig.jpeg\"><figcaption>UI</figcaption></figure><h3>Conclusion</h3>\n<p>Here I have showcased four steps to embed GitHub repositories on your React website. There are many react projects for embed GitHub repositories on your React website. But how this is different from other project cards is these cards show the color dots related to a programming language according to GitHub linguist. You can clone the Repo from this <a href=\"https://github.com/sabesansathananthan/react-github-repo-cards\">link</a>. If you are going to use this project then Don’t forget to give a star⭐️ for this repo.</p>\n<p>Happy Coding 😊 !!!</p>\n<img src=\"https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccefacc30f62\" width=\"1\" height=\"1\" alt=\"\"><hr>\n<p><a href=\"https://bootcamp.uxdesign.cc/embed-your-github-project-on-your-react-website-ccefacc30f62\">Embed your GitHub project on your React website</a> was originally published in <a href=\"https://bootcamp.uxdesign.cc/\">Bootcamp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>\n",
"content": "\n<h4>FRONT END</h4>\n<h4>Embed GitHub repo on your Website using Material-UI gives better UI</h4>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*2hWfwgI2WwfkkD4QNdUpbQ.jpeg\"><figcaption>Photo by <a href=\"https://unsplash.com/@markuswinkler?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Markus Winkler</a> on <a href=\"https://unsplash.com/s/photos/github?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Unsplash</a></figcaption></figure><blockquote>They say imitation is a form of flattery but honey, it is time to get your own ideas.</blockquote>\n<p>I thought to embed my GitHub projects on my <a href=\"https://sabesansathananthan.now.sh/\">website</a> like pinned repositories in GitHub. First I faced a problem that how could I get the programming language colors as shown in GitHub. Then I found that was defined in GitHub <a href=\"https://raw.githubusercontent.com/github/linguist/master/lib/linguist/languages.yml\">linguist</a>. But linguist file defined in YAML Therefore, I fetched that data and convert it to JSON. Therefore I created an API to fetch the linguist details. But In this article, I am not going to talk about that. If you want to watch the API repository click the <a href=\"https://github.com/sabesansathananthan/github-linguist-json\">link</a>. Here I will describe how I created the GitHub repository cards in React application. This is my 33rd Medium article.</p>\n<p>In this article, I am going to say how to start from scratch. Here you could see the live <a href=\"https://react-github-repo-cards.vercel.app/\">demo</a> of this react application. Now I finished this project and have a repo in GitHub.</p>\n<h3>Step1: Setup Project</h3>\n<p>First, you need to create a react application. For that run the following command in your shell/terminal in a specific folder (e.g., desktop )</p>\n<pre>npx create-react-app github-repo</pre>\n<p>A new folder will be created, and it will be named as a github-repo. From this step, our application is bootstrapped with <a href=\"https://github.com/facebook/create-react-app\">Create React App</a>. For more information, click the <a href=\"https://github.com/facebook/create-react-app\">link</a>. Then open that project in your IDE. I am personally using the VS Code IDE. You need to delete some files and organize the files for the development after you open the folder in your IDE. Therefore you need to go to the src folder and delete Logo.svg, App.css, index.css, and App.test.js files. And create the following folders inside the src folder named components and api.</p>\n<p>Now open the index.js file and delete the following snippet in index.js file.</p>\n<pre><em>import</em> ‘./index.css’;</pre>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*lxNhDY0lI5CcPIK8Wp4Owg.jpeg\"><figcaption>Photo by <a href=\"https://www.pexels.com/@dhayaeddart?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels\">Dhaya Eddine Bentaleb</a> from <a href=\"https://www.pexels.com/photo/wood-fashion-sunglasses-art-4935600/?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels\">Pexels</a></figcaption></figure><h3>Step 2: Install packages</h3>\n<p>Install Material-UI for Material Design form component.</p>\n<pre>npm install @material-ui/core --save</pre>\n<p>Install Axios to make HTTP requests to the API.</p>\n<pre>npm install axios --save</pre>\n<blockquote>\n<em>Note: Fetching JSON Data can be achieved through the fetch API in JavaScript. Reason for using Axios Even old browsers like IE11 can run Axios without any issue. </em><em>Fetch(), on the other hand, only supports Chrome 42+, Firefox 39+, Edge 14+, and Safari 10.1+ (you can see the full compatibly table on </em><a href=\"https://caniuse.com/#search=Fetch\"><em>Can I use</em></a><em>…)</em>\n</blockquote>\n<p>Open the index.html file in the public folder and paste the below code inside the <head> </head> tag.</p>\n<pre><link <em>rel</em>=”stylesheet” <em>href</em>=”https://cdnjs.cloudflare.com/ajax/libs/octicons/3.5.0/octicons.min.css\" /></pre>\n<p>the above process is not installing the package. You are going to use octionsCDN.</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*LCfjLo6fyEJisPOr4uNMgA.jpeg\"><figcaption>Photo by <a href=\"https://www.pexels.com/@cottonbro?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels\">cottonbro</a> from <a href=\"https://www.pexels.com/photo/woman-using-a-computer-5473298/?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels\">Pexels</a></figcaption></figure><h3>Step 3: Implementation</h3>\n<p>First thing first you need to go to GitHub and then go to the settings. Click the Developer Settings in the left column. Click the personal access token and generate a new token and copy that token. open your react project and create a new file in the root folder named .env. Inside the .env file add the following code. Replace your copied GitHub Personal Access Token instead of <em>Your_Personal_Access_Token .</em></p>\n<pre>REACT_APP_API_KEY = Your_Personal_Access_Token</pre>\n<p>Inside the api folder create a new file named Github.js. Add the following code in the Github.js file.</p>\n<a href=\"https://medium.com/media/80e2ea0abdf8baa91bda9b6cc2301bf8/href\">https://medium.com/media/80e2ea0abdf8baa91bda9b6cc2301bf8/href</a><p>Replace your GitHub user name instead of <em>sabesansathananthan</em> on line 2.</p>\n<p>Inside the components folder, create a new file named GitHubCards.js. Add the following code in the GitHubCards.js file.</p>\n<a href=\"https://medium.com/media/4d450a719f69aeb6a6601bcb0d0ec2bd/href\">https://medium.com/media/4d450a719f69aeb6a6601bcb0d0ec2bd/href</a><p>In line 28, You are fetching the linguist API using Axios and then you set your language state. Form line 31 to line 42, You are fetching GitHub API for each repository. From line 46 to 52, You are sorting repo array elements according to the stargazers_count (stars count).</p>\n<p>Inside the components folder, create a new file named RepoCard.js. Add the following code in the RepoCard.js file.</p>\n<a href=\"https://medium.com/media/8ab5dacde0fe37796ccd1c7848de3e03/href\">https://medium.com/media/8ab5dacde0fe37796ccd1c7848de3e03/href</a><p>The above functional component returns JSX elements and Material-UI components.</p>\n<p>Finally, Render the GitHubCards component in App.js, as shown below.</p>\n<a href=\"https://medium.com/media/3948aebd1ff6d2753e9994bc0aeca4d7/href\">https://medium.com/media/3948aebd1ff6d2753e9994bc0aeca4d7/href</a><figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*gD2Ef2dVWMHWA39cP3DJig.jpeg\"><figcaption>UI</figcaption></figure><h3>Conclusion</h3>\n<p>Here I have showcased four steps to embed GitHub repositories on your React website. There are many react projects for embed GitHub repositories on your React website. But how this is different from other project cards is these cards show the color dots related to a programming language according to GitHub linguist. You can clone the Repo from this <a href=\"https://github.com/sabesansathananthan/react-github-repo-cards\">link</a>. If you are going to use this project then Don’t forget to give a star⭐️ for this repo.</p>\n<p>Happy Coding 😊 !!!</p>\n<img src=\"https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccefacc30f62\" width=\"1\" height=\"1\" alt=\"\"><hr>\n<p><a href=\"https://bootcamp.uxdesign.cc/embed-your-github-project-on-your-react-website-ccefacc30f62\">Embed your GitHub project on your React website</a> was originally published in <a href=\"https://bootcamp.uxdesign.cc/\">Bootcamp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>\n",
"enclosure": {},
"categories": ["javascript", "ux", "github", "react", "web-development"],
"clapCount": 117,
"voterCount": 15,
"responseCount": 0,
"readingTime": 4
},
{
"title": "Embed Medium as a blog on your React Website — Part 2",
"pubDate": "2020-09-25 15:21:21",
"link": "https://medium.datadriveninvestor.com/embed-medium-as-a-blog-on-your-react-website-part-2-187db2b60a59?source=rss-b255948cc1f5------2",
"guid": "https://medium.com/p/187db2b60a59",
"author": "Sabesan Sathananthan",
"thumbnail": "https://cdn-images-1.medium.com/max/1024/1*Xem1rbG0Fa8DAhtez7mvsA.jpeg",
"description": "\n<h4>FRONT END</h4>\n<h3>Embed Medium as a blog on your React Website — Part 2</h3>\n<h4>Embed Medium on your Website using Material-UI gives better UI</h4>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*Xem1rbG0Fa8DAhtez7mvsA.jpeg\"><figcaption>Photo by <a href=\"https://unsplash.com/@aronvisuals?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Aron Visuals</a> on <a href=\"https://unsplash.com/?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Unsplash</a></figcaption></figure><p>I have already implemented Medium as a blog on my website. Before I <a href=\"https://react-medium-blog.web.app/\">used</a> shards-react. I have mentioned that method in my <a href=\"https://medium.com/datadriveninvestor/embedded-medium-as-a-blog-on-your-react-website-f01be289e151\">26th article</a>. But I like to make it better. I liked that user interface but not satisfied. So I thought about using Material-UI for better user experience. Here I am going to explain implemented it in pure JavaScript and React Js. Here you could see the live <a href=\"https://material-ui-medium-blog.vercel.app/\">demo</a> of this react application. This is my 32nd Medium article.</p>\n<p>I have already introduced<a href=\"https://towardsdatascience.com/react-best-practices-804def6d5215\"> React</a> and Medium in my previous articles. If you’ve missed, click those links and read them. I like to show my active hours on my blog page with a green badge. I like to migrate my blog components from <a href=\"https://github.com/DesignRevision/shards-react\">Shards-React</a> to <a href=\"https://github.com/mui-org/material-ui\">Material-UI</a>. Because Material-UI Components are looking attractive and easy to handle. Then I thought, why can’t I implement that in my blog page. Now I finished that and have a repo in GitHub. In this article, I am going to say how to start from scratch.</p>\n<h3>Step1: Setup React Project 🆕</h3>\n<p>First, you need to create a react application. For that run the following command in your shell/terminal in a specific folder (e.g., desktop )</p>\n<pre>npx create-react-app medium-post</pre>\n<p>A new folder will be created, and it will be named as a medium-post. From this step, our application is bootstrapped with <a href=\"https://github.com/facebook/create-react-app\">Create React App</a>. For more information, click the <a href=\"https://github.com/facebook/create-react-app\">link</a>. Then open that project in your IDE. I am personally using the VS Code IDE.</p>\n<h3>Step2: Delete Unwanted Files 🗑️</h3>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/326/1*UqZD2JOjwEk1cn1KSLz0RA.png\"><figcaption>Create React App file organization</figcaption></figure><p>You need to delete some files and organize the files for the development after you open the folder in your IDE. Therefore you need to go to the src folder and delete Logo.svg, App.css, index.css, and App.test.js files. And create the following folders inside the src folder named components, assets, helpers, and utils, then move your serviceWorker.js into the helper’s folder. App.js file into the Components folder.</p>\n<p>Now open the index.js file and delete the following snippet in index.js file.</p>\n<pre><em>import</em> ‘./index.css’;</pre>\n<p>Then modify the App.js and serviceWorker.js files paths in index.js import like following.</p>\n<pre><em>import</em> App <em>from</em> ‘./components/App’;<br><em>import</em> * <em>as</em> serviceWorker <em>from</em> ‘./helpers/serviceWorker’;</pre>\n<p>Go to the Components folder and open the App.js. Delete the return part of the App function. Now your file organization will be like below.</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/327/1*GTlwuOOEekUT_cUP8WcaPA.png\"></figure><h3>Step 3: Install packages 🔄</h3>\n<p>Install Material-UI for Material Design form component.</p>\n<pre>npm install @material-ui/core --save</pre>\n<p>Install Axios to make HTTP requests to the API.</p>\n<pre>npm install axios --save</pre>\n<blockquote>Note: Fetching JSON Data can be achieved through the fetch API in JavaScript. Reason for using Axios Even old browsers like IE11 can run Axios without any issue. <em>Fetch()</em>, on the other hand, only supports Chrome 42+, Firefox 39+, Edge 14+, and Safari 10.1+ (you can see the full compatibly table on <a href=\"https://caniuse.com/#search=Fetch\">Can I use</a>…)</blockquote>\n<p>Install react-fontawesome to display icons.</p>\n<pre>npm i @fortawesome/fontawesome-svg-core @fortawesome/free-solid-svg-icons @fortawesome/react-fontawesome --save</pre>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*7IatRIAgdnVwbhsHl3dvIQ.jpeg\"><figcaption>Photo by <a href=\"https://www.pexels.com/@divinetechygirl?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels\">Christina Morillo</a> from <a href=\"https://www.pexels.com/photo/photography-of-person-typing-1181675/?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels\">Pexels</a></figcaption></figure><h3>Step4: Fetch data from medium 🔗</h3>\n<p>Then create a new file named slider.js inside the components folder. Add the following code in the slider.js file.</p>\n<a href=\"https://medium.com/media/ae26c83dbccca8ef0a27ee38e970b517/href\">https://medium.com/media/ae26c83dbccca8ef0a27ee38e970b517/href</a><p>Replace your Medium user name instead of @Sabesan96 on line 13.</p>\n<p>Then create the utils folder and create the Totext.js file inside the utils folder. Add the following snippet in the Totext.js file.</p>\n<a href=\"https://medium.com/media/3a2968547087668a6750ea3f74b44a46/href\">https://medium.com/media/3a2968547087668a6750ea3f74b44a46/href</a><p>Then create the ShortenText.js file inside the utils folder and add the following snippet in the ShortenText.js file</p>\n<a href=\"https://medium.com/media/25d01e07701220c0490e751ba6ac8c2c/href\">https://medium.com/media/25d01e07701220c0490e751ba6ac8c2c/href</a><p>Create PostCard.js file inside the component folder and add the following snippet in the PostCard.js file.</p>\n<a href=\"https://medium.com/media/38965781049e775376bb3499f1477879/href\">https://medium.com/media/38965781049e775376bb3499f1477879/href</a><p>In the PostCard.js I achieved the active status badge. In there I use the <strong>Date()</strong> function to create an object in JavaScript with current date and time. And I conditionally render the component (line 140) according to my wake up time (5 am) and Bedtime (10 pm). Code section of line 110 - line133 is for date formatting.</p>\n<p>Finally, Render the Slider component in App.js, as shown below</p>\n<a href=\"https://medium.com/media/889182e6e9917020bbcda5a4d7414b28/href\">https://medium.com/media/889182e6e9917020bbcda5a4d7414b28/href</a><figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*78kuaL6cglT36narJUSvuw.png\"><figcaption>UI in sleeping hours</figcaption></figure><figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*Erf7s9JlxYhaLC1_4h9m6g.png\"><figcaption>UI in Active hours</figcaption></figure><h3>Conclusion</h3>\n<p>Here I have showcased four steps to embed Medium as a blog on your React Website. If you use this, you won’t spend money to embed medium. However, when you follow these methods, you will be unable to show your related medium posts section in your blog. You can clone the Repo from this <a href=\"https://github.com/sabesansathananthan/material-ui-medium-blog\">link</a>. If you are going to use this project then Don’t forget to give a star⭐️ for this repo.</p>\n<p>Happy Coding 😊 !!!</p>\n<p><strong><em>Thank you for reading this far. If you enjoyed this post, please share, comment, and press that 👏 a few times (up to 50 times). . . Maybe it will help someone.</em></strong></p>\n<p><strong><em>Follow me on </em></strong><a href=\"https://twitter.com/TheSabesan\"><strong><em>Twitter</em></strong></a><strong><em> and Medium if you’re interested in more in-depth and informative write-ups like these in the future!</em></strong></p>\n<h4>Gain Access to Expert View — <a href=\"https://datadriveninvestor.com/ddi-intel\">Subscribe to DDI Intel</a>\n</h4>\n<img src=\"https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=187db2b60a59\" width=\"1\" height=\"1\" alt=\"\"><hr>\n<p><a href=\"https://medium.datadriveninvestor.com/embed-medium-as-a-blog-on-your-react-website-part-2-187db2b60a59\">Embed Medium as a blog on your React Website — Part 2</a> was originally published in <a href=\"https://medium.datadriveninvestor.com/\">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>\n",
"content": "\n<h4>FRONT END</h4>\n<h3>Embed Medium as a blog on your React Website — Part 2</h3>\n<h4>Embed Medium on your Website using Material-UI gives better UI</h4>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*Xem1rbG0Fa8DAhtez7mvsA.jpeg\"><figcaption>Photo by <a href=\"https://unsplash.com/@aronvisuals?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Aron Visuals</a> on <a href=\"https://unsplash.com/?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText\">Unsplash</a></figcaption></figure><p>I have already implemented Medium as a blog on my website. Before I <a href=\"https://react-medium-blog.web.app/\">used</a> shards-react. I have mentioned that method in my <a href=\"https://medium.com/datadriveninvestor/embedded-medium-as-a-blog-on-your-react-website-f01be289e151\">26th article</a>. But I like to make it better. I liked that user interface but not satisfied. So I thought about using Material-UI for better user experience. Here I am going to explain implemented it in pure JavaScript and React Js. Here you could see the live <a href=\"https://material-ui-medium-blog.vercel.app/\">demo</a> of this react application. This is my 32nd Medium article.</p>\n<p>I have already introduced<a href=\"https://towardsdatascience.com/react-best-practices-804def6d5215\"> React</a> and Medium in my previous articles. If you’ve missed, click those links and read them. I like to show my active hours on my blog page with a green badge. I like to migrate my blog components from <a href=\"https://github.com/DesignRevision/shards-react\">Shards-React</a> to <a href=\"https://github.com/mui-org/material-ui\">Material-UI</a>. Because Material-UI Components are looking attractive and easy to handle. Then I thought, why can’t I implement that in my blog page. Now I finished that and have a repo in GitHub. In this article, I am going to say how to start from scratch.</p>\n<h3>Step1: Setup React Project 🆕</h3>\n<p>First, you need to create a react application. For that run the following command in your shell/terminal in a specific folder (e.g., desktop )</p>\n<pre>npx create-react-app medium-post</pre>\n<p>A new folder will be created, and it will be named as a medium-post. From this step, our application is bootstrapped with <a href=\"https://github.com/facebook/create-react-app\">Create React App</a>. For more information, click the <a href=\"https://github.com/facebook/create-react-app\">link</a>. Then open that project in your IDE. I am personally using the VS Code IDE.</p>\n<h3>Step2: Delete Unwanted Files 🗑️</h3>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/326/1*UqZD2JOjwEk1cn1KSLz0RA.png\"><figcaption>Create React App file organization</figcaption></figure><p>You need to delete some files and organize the files for the development after you open the folder in your IDE. Therefore you need to go to the src folder and delete Logo.svg, App.css, index.css, and App.test.js files. And create the following folders inside the src folder named components, assets, helpers, and utils, then move your serviceWorker.js into the helper’s folder. App.js file into the Components folder.</p>\n<p>Now open the index.js file and delete the following snippet in index.js file.</p>\n<pre><em>import</em> ‘./index.css’;</pre>\n<p>Then modify the App.js and serviceWorker.js files paths in index.js import like following.</p>\n<pre><em>import</em> App <em>from</em> ‘./components/App’;<br><em>import</em> * <em>as</em> serviceWorker <em>from</em> ‘./helpers/serviceWorker’;</pre>\n<p>Go to the Components folder and open the App.js. Delete the return part of the App function. Now your file organization will be like below.</p>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/327/1*GTlwuOOEekUT_cUP8WcaPA.png\"></figure><h3>Step 3: Install packages 🔄</h3>\n<p>Install Material-UI for Material Design form component.</p>\n<pre>npm install @material-ui/core --save</pre>\n<p>Install Axios to make HTTP requests to the API.</p>\n<pre>npm install axios --save</pre>\n<blockquote>Note: Fetching JSON Data can be achieved through the fetch API in JavaScript. Reason for using Axios Even old browsers like IE11 can run Axios without any issue. <em>Fetch()</em>, on the other hand, only supports Chrome 42+, Firefox 39+, Edge 14+, and Safari 10.1+ (you can see the full compatibly table on <a href=\"https://caniuse.com/#search=Fetch\">Can I use</a>…)</blockquote>\n<p>Install react-fontawesome to display icons.</p>\n<pre>npm i @fortawesome/fontawesome-svg-core @fortawesome/free-solid-svg-icons @fortawesome/react-fontawesome --save</pre>\n<figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*7IatRIAgdnVwbhsHl3dvIQ.jpeg\"><figcaption>Photo by <a href=\"https://www.pexels.com/@divinetechygirl?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels\">Christina Morillo</a> from <a href=\"https://www.pexels.com/photo/photography-of-person-typing-1181675/?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels\">Pexels</a></figcaption></figure><h3>Step4: Fetch data from medium 🔗</h3>\n<p>Then create a new file named slider.js inside the components folder. Add the following code in the slider.js file.</p>\n<a href=\"https://medium.com/media/ae26c83dbccca8ef0a27ee38e970b517/href\">https://medium.com/media/ae26c83dbccca8ef0a27ee38e970b517/href</a><p>Replace your Medium user name instead of @Sabesan96 on line 13.</p>\n<p>Then create the utils folder and create the Totext.js file inside the utils folder. Add the following snippet in the Totext.js file.</p>\n<a href=\"https://medium.com/media/3a2968547087668a6750ea3f74b44a46/href\">https://medium.com/media/3a2968547087668a6750ea3f74b44a46/href</a><p>Then create the ShortenText.js file inside the utils folder and add the following snippet in the ShortenText.js file</p>\n<a href=\"https://medium.com/media/25d01e07701220c0490e751ba6ac8c2c/href\">https://medium.com/media/25d01e07701220c0490e751ba6ac8c2c/href</a><p>Create PostCard.js file inside the component folder and add the following snippet in the PostCard.js file.</p>\n<a href=\"https://medium.com/media/38965781049e775376bb3499f1477879/href\">https://medium.com/media/38965781049e775376bb3499f1477879/href</a><p>In the PostCard.js I achieved the active status badge. In there I use the <strong>Date()</strong> function to create an object in JavaScript with current date and time. And I conditionally render the component (line 140) according to my wake up time (5 am) and Bedtime (10 pm). Code section of line 110 - line133 is for date formatting.</p>\n<p>Finally, Render the Slider component in App.js, as shown below</p>\n<a href=\"https://medium.com/media/889182e6e9917020bbcda5a4d7414b28/href\">https://medium.com/media/889182e6e9917020bbcda5a4d7414b28/href</a><figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*78kuaL6cglT36narJUSvuw.png\"><figcaption>UI in sleeping hours</figcaption></figure><figure><img alt=\"\" src=\"https://cdn-images-1.medium.com/max/1024/1*Erf7s9JlxYhaLC1_4h9m6g.png\"><figcaption>UI in Active hours</figcaption></figure><h3>Conclusion</h3>\n<p>Here I have showcased four steps to embed Medium as a blog on your React Website. If you use this, you won’t spend money to embed medium. However, when you follow these methods, you will be unable to show your related medium posts section in your blog. You can clone the Repo from this <a href=\"https://github.com/sabesansathananthan/material-ui-medium-blog\">link</a>. If you are going to use this project then Don’t forget to give a star⭐️ for this repo.</p>\n<p>Happy Coding 😊 !!!</p>\n<p><strong><em>Thank you for reading this far. If you enjoyed this post, please share, comment, and press that 👏 a few times (up to 50 times). . . Maybe it will help someone.</em></strong></p>\n<p><strong><em>Follow me on </em></strong><a href=\"https://twitter.com/TheSabesan\"><strong><em>Twitter</em></strong></a><strong><em> and Medium if you’re interested in more in-depth and informative write-ups like these in the future!</em></strong></p>\n<h4>Gain Access to Expert View — <a href=\"https://datadriveninvestor.com/ddi-intel\">Subscribe to DDI Intel</a>\n</h4>\n<img src=\"https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=187db2b60a59\" width=\"1\" height=\"1\" alt=\"\"><hr>\n<p><a href=\"https://medium.datadriveninvestor.com/embed-medium-as-a-blog-on-your-react-website-part-2-187db2b60a59\">Embed Medium as a blog on your React Website — Part 2</a> was originally published in <a href=\"https://medium.datadriveninvestor.com/\">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>\n",
"enclosure": {},
"categories": [
"material-design",
"web-development",
"javascript",
"react",
"blog"
],
"clapCount": 191,
"voterCount": 13,
"responseCount": 0,
"readingTime": 4
},
{
"title": "Serverless Material UI contact form",
"pubDate": "2020-09-18 16:24:44",
"link": "https://bootcamp.uxdesign.cc/serverless-material-ui-contact-form-55296e107609?source=rss-b255948cc1f5------2",
"guid": "https://medium.com/p/55296e107609",
"author": "Sabesan Sathananthan",
"thumbnail": "https://cdn-images-1.medium.com/max/2600/1*ZmmpN0pzGm7-WQQwoSTwHQ.jpeg",
"description": "<div class=\"medium-feed-item\">\n<p class=\"medium-feed-image\"><a href=\"https://bootcamp.uxdesign.cc/serverless-material-ui-contact-form-55296e107609?source=rss-b255948cc1f5------2\"><img src=\"https://cdn-images-1.medium.com/max/2600/1*ZmmpN0pzGm7-WQQwoSTwHQ.jpeg\" width=\"4460\"></a></p>\n<p class=\"medium-feed-snippet\">Setting up a serverless Material UI contact form — using Express and Nodemailer</p>\n<p class=\"medium-feed-link\"><a href=\"https://bootcamp.uxdesign.cc/serverless-material-ui-contact-form-55296e107609?source=rss-b255948cc1f5------2\">Continue reading on Bootcamp »</a></p>\n</div>",
"content": "<div class=\"medium-feed-item\">\n<p class=\"medium-feed-image\"><a href=\"https://bootcamp.uxdesign.cc/serverless-material-ui-contact-form-55296e107609?source=rss-b255948cc1f5------2\"><img src=\"https://cdn-images-1.medium.com/max/2600/1*ZmmpN0pzGm7-WQQwoSTwHQ.jpeg\" width=\"4460\"></a></p>\n<p class=\"medium-feed-snippet\">Setting up a serverless Material UI contact form — using Express and Nodemailer</p>\n<p class=\"medium-feed-link\"><a href=\"https://bootcamp.uxdesign.cc/serverless-material-ui-contact-form-55296e107609?source=rss-b255948cc1f5------2\">Continue reading on Bootcamp »</a></p>\n</div>",
"enclosure": {},
"categories": [
"react",
"javascript",
"material-design",
"full-stack",
"web-development"
],
"clapCount": 59,
"voterCount": 6,
"responseCount": 1,
"readingTime": 4
}
]
}