<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Jordan Jaramillo</title>
    <description>The latest articles on DEV Community by Jordan Jaramillo (@jordandev).</description>
    <link>https://dev.to/jordandev</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F527107%2F24edcea3-2cad-4965-842b-5a51fa4bb4c2.jpg</url>
      <title>DEV Community: Jordan Jaramillo</title>
      <link>https://dev.to/jordandev</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/jordandev"/>
    <language>en</language>
    <item>
      <title>Why Should You Prefer TypeScript over JavaScript in React.JS?</title>
      <dc:creator>Jordan Jaramillo</dc:creator>
      <pubDate>Fri, 24 Mar 2023 16:20:35 +0000</pubDate>
      <link>https://dev.to/jordandev/why-should-you-prefer-typescript-over-javascript-in-reactjs-2d1</link>
      <guid>https://dev.to/jordandev/why-should-you-prefer-typescript-over-javascript-in-reactjs-2d1</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;This post was generated by artificial intelligence.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;As a frontend developer, I have worked on multiple projects using both TypeScript and JavaScript. While both are great programming languages, TypeScript has become my go-to language when it comes to developing React applications. In this blog post, I'll explain why you should prefer TypeScript over JavaScript when working with React.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.educative.io%2Fv2api%2Feditorpage%2F5601688942542848%2Fimage%2F6688001464729600" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.educative.io%2Fv2api%2Feditorpage%2F5601688942542848%2Fimage%2F6688001464729600" alt="TypeScript with react.js"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Type Safety
&lt;/h3&gt;

&lt;p&gt;TypeScript is a statically typed language, which means that it catches type-related errors at compile time rather than runtime. This feature makes it easier to catch bugs early in the development cycle, reducing the risk of introducing bugs into production.&lt;/p&gt;

&lt;p&gt;In contrast, JavaScript is dynamically typed, which means that errors related to types may not be caught until runtime. This can lead to unexpected behavior and more time spent debugging.&lt;/p&gt;

&lt;p&gt;With TypeScript, you can use interfaces to define the shape of your data, making it easier to understand how data flows through your application. This feature can also help with code documentation and make it easier for other developers to understand your code.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Better IDE Support
&lt;/h3&gt;

&lt;p&gt;TypeScript has better IDE support than JavaScript. IDEs like Visual Studio Code have built-in support for TypeScript, which means that you get better code completion and error highlighting. This feature can save you a lot of time when developing and debugging your code.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Improved Maintainability
&lt;/h3&gt;

&lt;p&gt;TypeScript can help improve the maintainability of your codebase. With TypeScript, you can define interfaces and types for your data, making it easier to understand how data flows through your application. This feature can help you avoid code duplication and reduce the risk of introducing bugs when modifying your codebase.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. Easier Refactoring
&lt;/h3&gt;

&lt;p&gt;TypeScript makes refactoring easier. Since TypeScript catches type-related errors at compile time, you can refactor your codebase with more confidence, knowing that your code will still work after refactoring.&lt;/p&gt;

&lt;h3&gt;
  
  
  5. Community Support
&lt;/h3&gt;

&lt;p&gt;TypeScript has a large and active community that is continuously improving the language. This means that you can easily find support and resources when working with TypeScript, including libraries and frameworks built specifically for TypeScript.&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;While JavaScript is a great language, TypeScript has many features that make it a better choice when working with React. With TypeScript, you get type safety, better IDE support, improved maintainability, easier refactoring, and a large and active community.&lt;/p&gt;

&lt;p&gt;I highly recommend using TypeScript when developing React applications. By choosing TypeScript, you can create more robust and maintainable code, reducing the risk of introducing bugs into production and making it easier to scale your application as it grows.&lt;/p&gt;

</description>
      <category>react</category>
      <category>typescript</category>
      <category>javascript</category>
      <category>ai</category>
    </item>
    <item>
      <title>What is react-testing-library and what is it used for?</title>
      <dc:creator>Jordan Jaramillo</dc:creator>
      <pubDate>Fri, 03 Feb 2023 15:36:25 +0000</pubDate>
      <link>https://dev.to/jordandev/what-is-react-testing-library-and-what-is-it-used-for-1jp4</link>
      <guid>https://dev.to/jordandev/what-is-react-testing-library-and-what-is-it-used-for-1jp4</guid>
      <description>&lt;h1&gt;
  
  
  What is react-testing-library and what is it used for?
&lt;/h1&gt;

&lt;p&gt;react-testing-library is a testing library for React applications that focuses on testing the end-user experience rather than testing the internal logic of components. This library is easy to use and integrates seamlessly with React, making it ideal for testing React applications.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why use react-testing-library instead of other testing libraries?
&lt;/h2&gt;

&lt;p&gt;React-testing-library focuses on testing the application from the end user's perspective. This means that instead of focusing on testing individual components in isolation, it tests how the application behaves in its final form, including the interaction with the components.&lt;/p&gt;

&lt;p&gt;In addition, react-testing-library uses a "real-user-like" approach to its testing, which means that tests are performed with the same movements and actions that a real user would perform in the application. This makes the tests more accurate and ensures that the application behaves as expected in real situations.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to use react-testing-library?
&lt;/h2&gt;

&lt;p&gt;To use react-testing-library in your tests, you must first install the library via npm or yarn:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;npm &lt;span class="nb"&gt;install&lt;/span&gt; &lt;span class="nt"&gt;--save-dev&lt;/span&gt; react-testing-library
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once installed, you can write your tests using the API provided by react-testing-library. For example, to test a React component, you must first import the component and the library:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;React&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;react&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;render&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;fireEvent&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;react-testing-library&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;Button&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;./Button&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, you can use the render function to render the component in a test environment and perform your tests:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="nx"&gt;test&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Button component&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;onClick&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;jest&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;fn&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;getByText&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;render&lt;/span&gt;&lt;span class="p"&gt;(&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Button&lt;/span&gt; &lt;span class="na"&gt;onClick&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;onClick&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;Click me&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nc"&gt;Button&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;);&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;button&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;getByText&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Click me&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

  &lt;span class="nx"&gt;fireEvent&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;click&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;button&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

  &lt;span class="nx"&gt;expect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;onClick&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nx"&gt;toHaveBeenCalled&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the &lt;code&gt;render&lt;/code&gt; function is used to render the Button component in a test environment. Then, the &lt;code&gt;getByText&lt;/code&gt; function is used to get the button and the &lt;code&gt;fireEvent.click&lt;/code&gt; function is used to simulate a click on the button. Finally, the onClick function is verified to have been called with &lt;code&gt;expect(onClick).toHaveBeenCalled()&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;react-testing-library&lt;/code&gt; is a testing library for React applications that allows you to test the end-user experience effectively. It is easy to use and integrates seamlessly with React, making it ideal for testing React applications.&lt;/p&gt;

</description>
      <category>react</category>
      <category>testing</category>
      <category>javascript</category>
      <category>ai</category>
    </item>
    <item>
      <title>Typescript vs Javascript</title>
      <dc:creator>Jordan Jaramillo</dc:creator>
      <pubDate>Sat, 23 Apr 2022 01:25:46 +0000</pubDate>
      <link>https://dev.to/jordandev/typescript-vs-javascript-4iee</link>
      <guid>https://dev.to/jordandev/typescript-vs-javascript-4iee</guid>
      <description>&lt;p&gt;It is common to misunderstand Typescript and Javascript as if they were similar, which is why this tutorial will see the significant differences so that you can have a clear idea about these two languages.&lt;/p&gt;

&lt;h3&gt;
  
  
  What is Javascript?
&lt;/h3&gt;

&lt;p&gt;JavaScript is a programming or scripting language that allows you to implement complex functions on web pages, every time a web page does more than just sit there and display static information for you to see, it displays timely content updates, interactive maps , 2D/3D Graphics animation, scrolling video player machines, etc, you can bet Javascript is probably involved. It is the third layer of the cake of standard web technologies, two of which (HTML and CSS) we have covered in much more detail in other parts of the Learning Area.&lt;/p&gt;

&lt;h3&gt;
  
  
  What is Typescript
&lt;/h3&gt;

&lt;p&gt;TypeScript es un lenguaje de programación fuertemente tipado que se basa en JavaScript, lo que le brinda mejores herramientas a cualquier escala.&lt;/p&gt;

&lt;p&gt;Some key features include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Typescript is compatible with all JavaScript libraries and frameworks. Angular, a JavaScript framework used to build single-page applications, is entirely written in Typescript.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;With an increase in code complexity, JavaScript had to meet OOP requirements; thus, that led to the introduction of Typescript.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Typescript helps with faster code development, thus improving performance.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;All code in Javascript is fully valid Typescript code.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Advantages of Typescript over Javascript
&lt;/h3&gt;

&lt;p&gt;There are some improvements with Typescript that give it an edge over Javascript. Here is the list of advantages of Typescript over Javascript.&lt;/p&gt;

&lt;p&gt;At the time of development, Typescript introduces the compilation problems. This reduces the chances of runtime errors.&lt;/p&gt;

&lt;p&gt;Typescript is strongly typed or allows static typing. This means that Typescript allows you to check the correctness of the type at compile time. This in JavaScript, is not possible.&lt;/p&gt;

&lt;p&gt;TypeScript is nothing more than JavaScript with additional functions, that is ES6 functions. Some of these features are as follows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Interfaces&lt;/li&gt;
&lt;li&gt;Generic&lt;/li&gt;
&lt;li&gt;Namespaces&lt;/li&gt;
&lt;li&gt;null check&lt;/li&gt;
&lt;li&gt;Access Modifiers&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The team that develops some of the most popular open sources use Typescript for the development of these libraries. One of the most popular examples is Angular.&lt;/p&gt;

&lt;p&gt;This means that most of the documentation and examples of these frameworks, mainly Angular, are written with Typescript. Eventually this means that the applications that are developed using these libraries are made with Typescript.&lt;/p&gt;

&lt;p&gt;Angular is perhaps the most prominent example, practically all applications in Angular are written using Typescript, if you want to understand the framework thoroughly, you need to know Typescript.&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion and my personal opinion
&lt;/h3&gt;

&lt;p&gt;Learning Typescript introduces you to an amazing programming language, with even better development tools. Particularly Visual Studio Code will offer an interesting number of improvements to your development flow. Personally, this has helped me a lot to reduce my work times and the detection of errors increases drastically.&lt;/p&gt;

&lt;p&gt;The amazing thing about using Typescript is that you can quickly configure it in your project, most frameworks allow you to install a Typescript boilerplate where you will get everything configured automatically.&lt;/p&gt;

&lt;p&gt;This magnificent language is also supported by gigantic companies that are implementing it and also Microsoft who keeps it updated, so much so that it appears on the list of the most demanded languages in recent years.&lt;/p&gt;

&lt;p&gt;So, what are you waiting for to learn it?&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Image taken from &lt;a href="https://tsh.io/"&gt;https://tsh.io/&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>typescript</category>
      <category>javascript</category>
      <category>code</category>
    </item>
    <item>
      <title>NodeJS with ExpressJS and TypeScript part 2.</title>
      <dc:creator>Jordan Jaramillo</dc:creator>
      <pubDate>Thu, 21 Apr 2022 04:36:02 +0000</pubDate>
      <link>https://dev.to/jordandev/nodejs-with-expressjs-and-typescript-part-2-40lk</link>
      <guid>https://dev.to/jordandev/nodejs-with-expressjs-and-typescript-part-2-40lk</guid>
      <description>&lt;p&gt;In this second part we are going to see how to increase the development time with nodemon, so as not to have to compile every time we make a change in our server, since now as we have it if we make a change in the code we must interrupt the execution of our server and recompile it to start it, then to speed this up we will use nodemon which is a tool that will automatically restart the server every time it detects a change in our code without compiling.&lt;/p&gt;

&lt;p&gt;To install nodemos we have to execute the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i -D nodemon
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Remember that nodemon is to speed up development so we install only as a development dependency.&lt;/p&gt;

&lt;p&gt;Now that we have nodemon we are going to execute:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx nodemon ./src/index.ts
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will start our server without generating production code and when we make a change the server will automatically restart.&lt;/p&gt;

&lt;p&gt;I will change the console message when my server starts&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.listen(8000, () =&amp;gt; {
  console.log('Server on port 8000!');
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we will see the following console output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;❯ npx nodemon ./src/index.ts
[nodemon] 2.0.15
[nodemon] to restart at any time, enter `rs`
[nodemon] viewing path(s): *.*
[nodemon] seeing extensions: ts,json
[nodemon] starting `ts-node ./src/index.ts`
The application is listening on port 8000!
[nodemon] rebooting due to changes...
[nodemon] starting `ts-node ./src/index.ts`
Server on port 8000!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Done now if we can move much faster in our development.&lt;/p&gt;

&lt;p&gt;Finally I'm going to create a script in my package.json:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"hyphens": {
    "build": "npx tsc --project ./",
    "start": "node ./build/index.js",
    "dev": "nodemon ./src/index.ts",
    "test": "echo \"Error: no test specified\" &amp;amp;&amp;amp; exit 1"
  },
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see I have created dev command which only has nodemon, we don't use npx.&lt;/p&gt;

&lt;p&gt;npx : This command allows you to run an arbitrary command from an npm package (either one installed locally or obtained remotely), in a context similar to running it via npm run, so when you create a script in the package. json no longer need to prepend npx.&lt;/p&gt;

&lt;h3&gt;
  
  
  QueryParameters
&lt;/h3&gt;

&lt;p&gt;Query parameters are optional key-value pairs that appear to the right of the ? in a URL. For example, the following URL has two query parameters, rating and page, with respective values ​​​​of ASC and 2:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://example.com/articles?sort=ASC&amp;amp;page=2" rel="noopener noreferrer"&gt;http://example.com/articles?sort=ASC&amp;amp;page=2&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this url we see that we have 2 query params which take the name of "sort" and "page" you can send many query params but they must be separated by the "&amp;amp;" and to assign a value with the "="&lt;/p&gt;

&lt;p&gt;Query parameters allow additional application state to be serialized to the URL that would not otherwise fit in the URL path (ie everything to the left of the ?). Common use cases for query parameters include rendering the current page number in a paginated collection, filter criteria, or sort criteria.&lt;/p&gt;

&lt;p&gt;In web development, query parameters are used within a URL as described above, but they can also be used in API requests that retrieve data. Ember treats them as two different concepts.&lt;/p&gt;

&lt;h3&gt;
  
  
  Dynamic response via query params
&lt;/h3&gt;

&lt;p&gt;Now we are going to see how we can return a string sent by the params of our request in the endpoint of type get that we created.&lt;/p&gt;

&lt;p&gt;Previously we only returned hello world but now we are going to return a name that the user will provide us through the example query params:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;http://localhost:8000?name=jordan
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our answer should be:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;hello jordan
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's see how we can do it.&lt;/p&gt;

&lt;p&gt;In our endpoint we have a callback that takes a req (Request) and res (Response) in the request we have a very large object which brings information about the request made by the user.&lt;/p&gt;

&lt;p&gt;Let's print req (Request) to the console:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.get('/', (req: Request, res: Response) =&amp;gt; {
  console.log(req);
  res.send('Hello World');
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let's reload our server page with the following query param :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;http://localhost:8000?name=jordan
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's see the console :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;baseUrl: '',
  originalUrl: '/?name=jordan',
  _parsedUrl: Url {
    protocol: null,
    slashes: null,
    auth: null,
    host: null,
    port: null,
    hostname: null,
    hash: null,
    search: '?name=jordan',
    query: 'name=jordan',
    pathname: '/',
    path: '/?name=jordan',
    href: '/?name=jordan',
    _raw: '/?name=jordan'
  },
  params: {},
  query: { name: 'jordan' },
  res: &amp;lt;ref *3&amp;gt; ServerResponse {
    _events: [Object: null prototype] { finish: [Function: bound resOnFinish] },
    _eventsCount: 1,
    _maxListeners: undefined,
    outputData: [],
    outputSize: 0,
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is a small part of that immense object but let's see a part that matters a lot to us since we have valuable information.&lt;/p&gt;

&lt;p&gt;As you can see we have the base url that as it is / does not show us anything, we have the href, original url and we also have the query params:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;query: { name: 'jordan' },
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So it means that we can access this by:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;res.query.name
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we already have the answer to our exercise, we only have to validate since the query params are optional, so we will do an if in our endpoint and it will be as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.get('/', (req: Request, res: Response) =&amp;gt; {
  if (req.query.name) {
    res.send(`Hello ${req.query.name}`);
  } else {
    res.send('Hello guest');
  }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we can answer the same thing in json with res.json({message : "message"})&lt;/p&gt;

&lt;p&gt;To implement it in our exercise it would be:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.get('/', (req: Request, res: Response) =&amp;gt; {
  if (req.query.name) {
    // res.send(`Hello ${req.query.name}`); send response type text
    res.json({ message: `Hello ${req.query.name}` }); //send response type json
  } else {
    // res.send('Hello guest'); send response type text
    res.json({ message: 'Hello guest' }); //send response type json
  }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What this will do is that if you do not send a name, it will reply "hello guest"&lt;/p&gt;

&lt;p&gt;Let's see how it turned out:&lt;br&gt;
With query param:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1650515333%2FScreen_Shot_2022-04-20_at_23.28.37_jvshhn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1650515333%2FScreen_Shot_2022-04-20_at_23.28.37_jvshhn.png" alt="named "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Without query param:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1650515366%2FScreen_Shot_2022-04-20_at_23.29.14_jqvvmq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1650515366%2FScreen_Shot_2022-04-20_at_23.29.14_jqvvmq.png" alt="no name"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In case you are wondering why my browser looks like this when I answer json, it is because of this extension: &lt;a href="https://chrome.google.com/webstore/detail/json-viewer/gbmdgpbipfallnflgajpaliibnhdgobh/related?hl=es" rel="noopener noreferrer"&gt;json viewer&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Challenge
&lt;/h3&gt;

&lt;p&gt;As a challenge I would like you to send more properties and send them all in the response as json. Leave me your solution in the comments is much easier than it seems.&lt;/p&gt;

&lt;p&gt;Remember that you don't know what property the user can submit, I'm excited to see your answer.&lt;/p&gt;

&lt;p&gt;In the next blog we will see how to respond to arrays of the amount specified by the user and we will also see the posts verb.&lt;/p&gt;

&lt;p&gt;So if you have any questions or recommendations comment. Remember to meet the challenge and show yourself that you can.&lt;/p&gt;

&lt;p&gt;You can access the code from the &lt;a href="https://github.com/jordanrjdev/express-typescript" rel="noopener noreferrer"&gt;repository&lt;/a&gt;. &lt;/p&gt;

</description>
      <category>node</category>
      <category>express</category>
      <category>typescript</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Node 18 is now available!!! 😎</title>
      <dc:creator>Jordan Jaramillo</dc:creator>
      <pubDate>Wed, 20 Apr 2022 02:37:06 +0000</pubDate>
      <link>https://dev.to/jordandev/node-18-is-now-available-3ld6</link>
      <guid>https://dev.to/jordandev/node-18-is-now-available-3ld6</guid>
      <description>&lt;p&gt;In this little post we will be testing a new feature of nodeJS 18.&lt;br&gt;
Node.js 18 will be promoted to Long Term Support (LTS) in October 2022.&lt;/p&gt;

&lt;p&gt;For the Node.js 18 release, I'll highlight some of the new features.&lt;/p&gt;

&lt;p&gt;Exciting new features include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Experimental Fetch&lt;/li&gt;
&lt;li&gt;Test Runner&lt;/li&gt;
&lt;li&gt;ECMAScript modules improvements&lt;/li&gt;
&lt;li&gt;Improved support for AbortController and AbortSignal&lt;/li&gt;
&lt;li&gt;Updated Platform Support&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Among other features.&lt;/p&gt;

&lt;p&gt;Today we are going to be doing some examples with testing where we will also be testing fetch, Array.findLast and Array.findLastIndex in a superficial way.&lt;/p&gt;
&lt;h2&gt;
  
  
  You can get all the code from this &lt;a href="https://github.com/jordanrjdev/node18"&gt;repository&lt;/a&gt;
&lt;/h2&gt;
&lt;h2&gt;
  
  
  Getting started
&lt;/h2&gt;

&lt;p&gt;So let's create our package.json with the command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm init -y
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Remember that you must install version 18 of node from the &lt;a href="https://nodejs.org"&gt;official page&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we are going to create a file which will be the index.js where we are going to start writing our tests.&lt;/p&gt;

&lt;p&gt;To start let's see what we have to import:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import test from "node:test";
import assert from "node:assert";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We see that we have 2 apis that come have to be prefixed to &lt;code&gt;node:&lt;/code&gt; or it won't work for you.&lt;/p&gt;

&lt;p&gt;Once importing this we can now write our first test.&lt;/p&gt;

&lt;h3&gt;
  
  
  Test a string:
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test("Testing a string", () =&amp;gt; {
   assert.match("Welcome Node 18", /Node 18/);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This test will give us the following output :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ok 1 - Testing a string
  ---
  duration_ms: 0.000385918
  ...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First what we will do is use the tests method which receives the description as the first parameter and a callback as the second parameter which will have the logic of our test or we can even execute subtest as indicated in the official documentation&lt;/p&gt;

&lt;p&gt;To assert a string we have to pass the string we want to test as the first parameter and as the second parameter we send the regular expression as we saw in the previous code.&lt;/p&gt;

&lt;p&gt;We can also send a third parameter which is optional but will serve as a custom error message. Let's see the example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test("Testing a string fails", () =&amp;gt; {
   assert.match("Hello", /world/, 'This string does not contain "world"');
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This test will give us the following output :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;❯node index.test.js 
not ok 1 - Testing a string fails
  duration_ms: 0.000888784
  failureType: 'testCodeFailure'
  error: 'This string not contains "world"'
  code: ERR_ASSERTION
  stack: |-
    TestContext.&amp;lt;anonymous&amp;gt; (file:///Users/jordandev/Desktop/node18/index.test.js:5:10)
    Test.runInAsyncScope (node:async_hooks:202:9)
    Test.run (node:internal/test_runner/test:333:20)
    Test.start (node:internal/test_runner/test:287:17)
    Test.test (node:internal/test_runner/harness:126:18)
    file:///Users/jordandev/Desktop/node18/index.test.js:4:1
    ModuleJob.run (node:internal/modules/esm/module_job:198:25)
    async Promise.all (index 0)
    async ESMLoader.import (node:internal/modules/esm/loader:409:24)
    async loadESM (node:internal/process/esm_loader:85:5)
  ...
  tests 1
  pass 0
  fail 1
  skipped 0
  todo 0
  duration_ms 0.062970366

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see in the error our custom error appears. &lt;/p&gt;

&lt;h3&gt;
  
  
  equal and notEqual
&lt;/h3&gt;

&lt;p&gt;Now we will see the equal and notEqual methods which will allow us to test 2 values to know if they are equal and not equal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test("Testing that a number is equal", () =&amp;gt; {
   let current = 99;
   let expected = 99;
   assert.equal(actual, expected);
});

test("Testing that a number is not equal", () =&amp;gt; {
   let current = 22;
   let expected = 393;
   assert.notEqual(actual, expected, `${actual} is not equal to ${expected}`);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, the 2 receive the current value as the first parameter and the expected value as the second parameter.&lt;/p&gt;

&lt;p&gt;Remember to run the test with&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;node index.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  deepStrictEqual
&lt;/h3&gt;

&lt;p&gt;We are going to test an object, for this we are going to use the deepStrictEqual method that will help us to deeply test the properties of our object:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test("Testing objects", () =&amp;gt; {
   assert.deepStrictEqual(
     { name: "jordan" },
     { name: "jordan" },
     "Objects are not equal"
   );
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Testing asynchronous functionality
&lt;/h3&gt;

&lt;p&gt;To test an asynchronous function we only have to use the asynchronous callback and in this way we can use await to be able to resolve promises:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test("Testing asynchronous functionality", async() =&amp;gt; {
   const number = await Promise.resolve(90);
   assert.equal(number, 90, "The number is not equal to 90");
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Array.findLast and Array.findLastIndex
&lt;/h3&gt;

&lt;p&gt;Now we are going to try the Array.findLast method, what we will do is create an array of numbers from 1 to 10 and we will look for the last multiple of 3 and as a result we should obtain 9&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test("Array.findLast", () =&amp;gt; {
     constant numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
     const lastmultipleofthree = numbers.findlast((n) =&amp;gt; n % 3 === 0);
     assert.equal(lastMultipleOfThree, 9);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The findLast method is similar in syntax to a filter but it will return the last element found.&lt;/p&gt;

&lt;p&gt;Now we will see the operation of the Array.findLastIndex method, we will have an array with repeated numbers and we will look for the last index of the element that is equal to 3, in this case it should be 9 according to the array that we will pass to it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test("Array.findLastIndex", () =&amp;gt; {
   const numbers = [1, 3, 2, 4, 4, 3, 4, 1, 9, 3];
   const lastIndexOfThree = numbers.findLastIndex((n) =&amp;gt; n === 3);
   assert.equal(lastIndexOfThree, 9);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This works similar to findIndex but returns the last found index of an element based on the condition.&lt;/p&gt;

&lt;h3&gt;
  
  
  Fetch
&lt;/h3&gt;

&lt;p&gt;Now we are going to try one of my favorite features which is fetch.&lt;/p&gt;

&lt;p&gt;Let's make a call to the jsonplaceholder api endpoint &lt;a href="https://jsonplaceholder.typicode.com/users/1"&gt;https://jsonplaceholder.typicode.com/users/1&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test("Fetch", async() =&amp;gt; {
   const reponse = await fetch("https://jsonplaceholder.typicode.com/users/1");
   const json = await response.json();
   assert.equal(json.name, "Leanne Graham");
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As we can see we have the fetch functionality just as we would from the browser.&lt;/p&gt;

&lt;p&gt;I have personally loved this and can't wait for it to be stable.&lt;/p&gt;

&lt;h3&gt;
  
  
  Subtests
&lt;/h3&gt;

&lt;p&gt;Finally we are going to do a subtest so that you have an example of how to do it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test("top level test", async (t) =&amp;gt; {
   await t.test("subtest 1", (t) =&amp;gt; {
     assert.strictEqual(1, 1);
   });

   await t.test("subtest 2", (t) =&amp;gt; {
     assert.strictEqual(2, 2);
   });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This example is offered by the official nodejs documentation. As you can see, it is very easy to chain tests through the parameter that the callback gives you.&lt;/p&gt;

&lt;p&gt;So having this clear, you can try out the new node. Personally, I really liked that they incorporate the test and node api.&lt;/p&gt;

&lt;p&gt;We cannot fail to mention the new methods for Arrays that will surely be super useful.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;If you want to know more about this update you can see it from the &lt;a href="https://nodejs.org/en/blog/announcements/v18-release-announce/"&gt;official blog here&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>node</category>
      <category>javascript</category>
      <category>code</category>
    </item>
    <item>
      <title>NodeJS with ExpressJS and TypeScript part 1.</title>
      <dc:creator>Jordan Jaramillo</dc:creator>
      <pubDate>Tue, 19 Apr 2022 02:42:07 +0000</pubDate>
      <link>https://dev.to/jordandev/nodejs-with-expressjs-and-typescript-part-1-18ob</link>
      <guid>https://dev.to/jordandev/nodejs-with-expressjs-and-typescript-part-1-18ob</guid>
      <description>&lt;h2&gt;
  
  
  NodeJS with ExpressJS and TypeScript part 1.
&lt;/h2&gt;

&lt;p&gt;In this post we will see how to create a server with expressJS and typescript from scratch, this post will be divided into several parts to make it understandable and explain each thing thoroughly.&lt;/p&gt;

&lt;h4&gt;
  
  
  You can access the code from the &lt;a href="https://github.com/jordanrjdev/express-typescript" rel="noopener noreferrer"&gt;repository&lt;/a&gt;
&lt;/h4&gt;

&lt;h2&gt;
  
  
  Getting started
&lt;/h2&gt;

&lt;p&gt;The first step to start a project in nodeJS we go with this command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm init -y 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command will start our project by creating the file &lt;strong&gt;package.json&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;Now we have to install the dependencies, for this case I am going to use express with typescript, let's see which are the dependencies that we are going to install:&lt;/p&gt;

&lt;p&gt;Dependencies: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;express&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Dev Dependencies: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;typescript&lt;/li&gt;
&lt;li&gt;ts-node&lt;/li&gt;
&lt;li&gt;@types/node&lt;/li&gt;
&lt;li&gt;@types/express&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Why do we install everything related to Typescript as devDependencies? Okay, let's remember that even though we'll be writing the code using Typescript, the code is recompiled into standard JavaScript. So Typescript is not needed per se to run the app, we only need it while we are developing this is why it is saved as a development dependency.&lt;/p&gt;

&lt;p&gt;So let's run the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install express 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;br&gt;
 &lt;/p&gt;

&lt;p&gt;and :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install -D typescript ts-node @types/node @types/express 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once we have successfully installed all the dependencies our package.json should look something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
   "name": "nodejs",
   "version": "1.0.0",
   "description": "",
   "main": "index.js",
   "scripts": {
     "test": "echo \"Error: no test specified\" &amp;amp;&amp;amp; exit 1"
   },
   "keywords": [],
   "author": "",
   "license": "ISC",
   "dependencies": {
     "express": "^4.17.3"
   },
   "devDependencies": {
     "@types/express": "^4.17.13",
     "@types/node": "^17.0.25",
     "ts-node": "^10.7.0",
     "typescript": "^4.6.3"
   }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Remember that the versions can change depending on when you read this post.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Configure TypeScript
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx tsc --init
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The tsconfig.json file that we created with the previous command contains a lot of code, and much of this same code is commented out so that you can experiment and configure it to your liking. However, there are a few settings I want to explain:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;module&lt;/strong&gt;: with this option, you can specify which module manager to use in the generated JavaScript code. such as : 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020' or 'ESNext'. The most common and default module manager is commonjs.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;target&lt;/strong&gt;: using this option, we can specify which version of ECMAScript to use in your project. Available versions are 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020' or 'ESNEXT'.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;outDir&lt;/strong&gt;: with this option, we can specify in which route the Javascript code will be generated.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;rootDir&lt;/strong&gt;: this option is where we specify where the TypeScript files are located.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;strict&lt;/strong&gt;: The option is enabled by default and enables strict type checking options.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can read more about this configuration in the tsconfig.json file itself or also from the official typescript documentation.&lt;/p&gt;

&lt;p&gt;In my case I will use the following configuration in tsconfig.json:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es6",
    "rootDir": "src/",
    "outDir": "./build",
    "strict": true
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Our first server with expressJS
&lt;/h2&gt;

&lt;p&gt;With typescript set up, it's time to create our first web server with expressJS. Let's create a file called index.ts.&lt;/p&gt;

&lt;p&gt;In this file we will have the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import express, { Request, Response } from 'express';
const app = express();

app.get('/', (req: Request, res: Response) =&amp;gt; {
  res.send('Hello World');
});

app.listen(8000, () =&amp;gt; {
  console.log('The application is listening on port 8000!');
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First what we do is import express from express along with the Request and Response types.&lt;/p&gt;

&lt;p&gt;Once this is done we have to initialize our app with the line&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const app = express();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we are going to add a get type endpoint in which a message will be returned, so we have to do the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.get("/");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To start in a simple way we will have our app and then we will put the method of our endpoint in this case &lt;strong&gt;get&lt;/strong&gt; this is a function which receives 2 parameters to start, then we can add middleware to it but at the moment there are 2 which the first it is a string with the route as we want it to be our initial route we just have to put a / and express understands that this will be our main route.&lt;/p&gt;

&lt;p&gt;Now we have to add the second parameter which is a callback, this callback receives 2 parameters which is request and response :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.get('/', (req: Request, res: Response) =&amp;gt; {
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, I have already added the types. Remember that you give the name to the 2 parameters, but by convention and the most common that you will find are req and res.&lt;/p&gt;

&lt;p&gt;Inside this callback our code will go, which will be executed when we access the route for now we will respond only text:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.get('/', (req: Request, res: Response) =&amp;gt; {
  res.send('Hello World');
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With &lt;strong&gt;res.send('Hello World');&lt;/strong&gt; what we do is tell it to respond with text to our call.&lt;/p&gt;

&lt;p&gt;Now let's see this in the browser. But before doing so we need one thing, which is to tell our express server (app) to keep listening on a certain port.&lt;/p&gt;

&lt;p&gt;So we will write:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.listen(8000, () =&amp;gt; {
  console.log('The application is listening on port 8000!');
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This receives 2 parameters, the first the port where our server will be listening and a callback which will be executed when the server is ready, for now we will only put a console.log.&lt;/p&gt;

&lt;p&gt;Taking this into account we are going to execute our server.&lt;/p&gt;

&lt;p&gt;Remember that since we are working with typescript we must compile to js so that node can read it, we execute the command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx tsc --project ./
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A build folder will be generated. which will have our code. which we may not understand but is already compiled.&lt;/p&gt;

&lt;p&gt;To speed up the compilation of our code we can create a script in our package.json in the scripts section:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"scripts": {
     "build": "npx tsc --project ./",
     "test": "echo \"Error: no test specified\" &amp;amp;&amp;amp; exit 1"
   },
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I have called it build now to compile we just have to execute:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm run build
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Whenever we create a script we have to execute it with:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; npm + run + script name
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At this point we can write the command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;node ./build/index.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We will see the following output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;❯ node ./build/index.js
The application is listening on port 8000!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's look at our web browser:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1650335533%2FScreen_Shot_2022-04-18_at_21.31.18_b6l6r0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1650335533%2FScreen_Shot_2022-04-18_at_21.31.18_b6l6r0.png" alt="web browser"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As we can see we have the response from our endpoint.&lt;/p&gt;

&lt;p&gt;As you could see in this article we have created our first server with expressJS and typescript.&lt;/p&gt;

&lt;p&gt;In the next part we will see how to speed up development using nodemon and we will also see how to respond to different types of formats. Requests with other http verbs and more.&lt;/p&gt;

&lt;p&gt;If you have any questions about this post, you can leave it in the comments. Or also if you have any recommendation you could leave it anyway. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The next part of this post will be available on April 19.&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>express</category>
      <category>node</category>
      <category>javascript</category>
      <category>typescript</category>
    </item>
    <item>
      <title>How to use async/await with .map in js</title>
      <dc:creator>Jordan Jaramillo</dc:creator>
      <pubDate>Sat, 16 Apr 2022 01:13:59 +0000</pubDate>
      <link>https://dev.to/jordandev/how-to-use-asyncawait-with-map-in-js-2ena</link>
      <guid>https://dev.to/jordandev/how-to-use-asyncawait-with-map-in-js-2ena</guid>
      <description>&lt;h2&gt;
  
  
  How to use async/await with .map in js
&lt;/h2&gt;

&lt;p&gt;At some point you may have wondered how to use asynchronous functions in methods like .map or .forEach, because in this little blog you will see what the most common errors are and how to solve them.&lt;/p&gt;

&lt;p&gt;For this we will have the following base code in the index.ts file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const usernames: string[] = ["jordanrjdev", "anonymous123", "channelyy"];

const simulateFetchData = (username: string): Promise&amp;lt;string&amp;gt; =&amp;gt; {
  return new Promise((resolve) =&amp;gt; {
    setTimeout(() =&amp;gt; {
      resolve(`${username} is a valid username`);
    }, 1000);
  });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see we have an array of usernames and a function that takes a parameter and returns a string.&lt;/p&gt;

&lt;p&gt;Now we will iterate the array of usernames to obtain the simulated data of each user with the map method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const dataUsers = usernames.map(async (username) =&amp;gt; {
   return await simulateFetchData(username);
});
console.log(dataUsers);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But when executing this we will see in the console the following result:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[ Promise { &amp;lt;pending&amp;gt; }, Promise { &amp;lt;pending&amp;gt; }, Promise { &amp;lt;pending&amp;gt; } ]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So to solve it we have 2 options, which are to use &lt;strong&gt;Promise.all&lt;/strong&gt; or use a &lt;strong&gt;for of&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  For of
&lt;/h2&gt;

&lt;p&gt;We are going to use a for of to be able to solve this error that is very common and can make us lose a lot of time when trying to find the most appropriate solution.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const getWithForOf = async() =&amp;gt; {
   console.time("for of");
   const data = []
   for (const username of usernames) {
     let dataUser = await simulateFetchData(username);
     data.push(dataUser);
   }
   console.timeEnd("for of");
}
getWithForOf();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With this option the code will be executed sequentially, so you can wait for each call. This will help us get each iteration resolved before moving on to the next.&lt;/p&gt;

&lt;p&gt;Keep in mind that if we do an N number of iterations and each of these takes 1 second to resolve, as in our example, it means that it will take a total of 3 seconds to finish executing this portion of code. We can see this in the console output thanks to console.time :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for of: 3,012s
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Promise.all
&lt;/h2&gt;

&lt;p&gt;Now we will use the promise.all method to solve our problem, so we will have the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const getWithPromiseAll = async() =&amp;gt; {
   console.time("promise all");
   let data = await Promise.all(usernames.map(async (username) =&amp;gt; {
     return await simulateFetchData(username);
   }))
   console.timeEnd("promise all");
}

getWithPromiseAll();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see we have a Promise.all method which receives an array of promises, remember that the&lt;br&gt;
&lt;br&gt;
 &lt;code&gt;usernames.map(async (username) =&amp;gt; {return await simulateFetchData(username);})&lt;/code&gt;&lt;br&gt;
&lt;br&gt;
 returns an array of promises, just what we need so we pass it to Promise.all to resolve them.&lt;/p&gt;

&lt;p&gt;This method will cause all asynchronous code to be resolved in parallel.&lt;/p&gt;

&lt;p&gt;So unlike the for of, let's see how long it takes to execute this function in the console:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;promise all: 980.3000000119209ms
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So if we have a number N of asynchronous functions, they will be executed and resolved without waiting between them, which can come in handy in some specific case.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Sometimes for performance reasons we will need to execute our promises in parallel with Promise.all and other times we will need to do it in sequence with the for of loop. &lt;strong&gt;The important thing is that you understand the difference between each one&lt;/strong&gt; and how to adapt it to your needs.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;If you have any questions or suggestions do not forget to comment, see you soon :)&lt;/p&gt;

&lt;p&gt;You can see the complete code in this codesandbox repository&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://codesandbox.io/embed/8tplrx"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>promises</category>
      <category>typescript</category>
    </item>
    <item>
      <title>Making a Post API in Laravel</title>
      <dc:creator>Jordan Jaramillo</dc:creator>
      <pubDate>Fri, 18 Mar 2022 20:30:28 +0000</pubDate>
      <link>https://dev.to/jordandev/making-a-post-api-in-laravels-4abm</link>
      <guid>https://dev.to/jordandev/making-a-post-api-in-laravels-4abm</guid>
      <description>&lt;h1&gt;
  
  
  Making a Post API in Laravel
&lt;/h1&gt;

&lt;p&gt;Making an api using laravel is very simple and makes it much easier for us to develop, it also helps you understand and apply good programming practices.&lt;/p&gt;

&lt;p&gt;So in this example we are going to make an api on posts, which we are going to have with authentication and in the end you are going to have a challenge which I will explain to you later as we advance with the project!&lt;/p&gt;

&lt;h2&gt;
  
  
  Starting with the project
&lt;/h2&gt;

&lt;p&gt;To create a project with Laravel from scratch we will start by going to the console and write the following command:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

composer create-project --prefer-dist laravel/laravel apiposts


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now we have a project created we are going to connect it to our database we do this in our .env file: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=apipost
DB_USERNAME=root
DB_PASSWORD=root


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Ready we have our database connected now we are going to create the models we need, in Laravel we have the migrations that are the versions of our database. This has many benefits when we develop as a team since we will be able to know what changes were made in the base and in case of errors we can roll back to a previous version.&lt;/p&gt;

&lt;p&gt;Laravel already brings default migrations that we can alter to our liking, in our case we will create a new one as follows:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

php artisan make:migration create_posts_table


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now we have our migration but some more things are missing like controller, model, seeders, factory, request that will help us with our project.&lt;br&gt;
We can create them one by one with the artisan commands but Laravel allows us to automate this and create everything with a single command, we are going to delete the migration of posts that we have created.&lt;/p&gt;

&lt;p&gt;And let's run the command:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

php artisan make:model Post --all


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;This command will create Model, factory, seeder, requests, controller and policy. &lt;/p&gt;

&lt;p&gt;We'll use them in a moment, but first we'll go to the database/migrations folder and open the last migration that was done and we'll see something like this:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table-&amp;gt;id();
            $table-&amp;gt;timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
};


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;Inside the up function we are going to define our table fields, the fields that we will use for now will be id, title, content, deleted_at and the timestamps that are created_at and updated_at by default. &lt;/p&gt;

&lt;p&gt;So our function would look like this:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table-&amp;gt;id();
            $table-&amp;gt;string('title');
            $table-&amp;gt;text('content');
            $table-&amp;gt;dateTime('deleted_at')-&amp;gt;nullable();
            $table-&amp;gt;timestamps();
        });
    }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;Ready now we have our migration ready, now for this to be reflected in our database we have to run a command, remember that the database you configured must already be created, but without any table.&lt;/p&gt;

&lt;p&gt;run migrations:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

php artisan migrate


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;blockquote&gt;
&lt;p&gt;As you can see all our tables have names in the plural and our model in the singular due to the convention used by Laravel, I recommend that all the models and tables have names in English to follow the convention.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1647625080%2FScreen_Shot_2022-03-18_at_12.36.02_dc43sj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1647625080%2FScreen_Shot_2022-03-18_at_12.36.02_dc43sj.png" alt="Tables of apipost database"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The next thing we are going to do is fill our post table with fake data to be able to develop the list method and not do inserts in our database since it is tedious, for this we can use the Laravel factories so, we have already created our factory thanks to the command we used above but don't worry you can create others with the command ```php&lt;br&gt;
&lt;br&gt;
 aritsan make:factory NameFactory&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
In our databases/factories/PostFactory file we have a method called definition inside the return we can do the following:

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;public function definition()&lt;br&gt;
     {&lt;br&gt;
         return [&lt;br&gt;
             'title' =&amp;gt; $this-&amp;gt;faker-&amp;gt;sentence,&lt;br&gt;
             'content' =&amp;gt; $this-&amp;gt;faker-&amp;gt;paragraph,&lt;br&gt;
             'deleted_at' =&amp;gt; null,&lt;br&gt;
         ];&lt;br&gt;
     }&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
What this will do is use faker to be able to fill our table with fake data but now we have to call it and use this we use it in the database/seeders/DatabaseSeeders file:

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&amp;lt;?php&lt;/p&gt;

&lt;p&gt;namespace Database\Seeders;&lt;/p&gt;

&lt;p&gt;use Illuminate\Database\Seeder;&lt;/p&gt;

&lt;p&gt;class DatabaseSeeder extends Seeder&lt;br&gt;
{&lt;br&gt;
    /**&lt;br&gt;
     * Seed the application's database.&lt;br&gt;
     *&lt;br&gt;
     * @return void&lt;br&gt;
     */&lt;br&gt;
    public function run()&lt;br&gt;
    {&lt;br&gt;
        \App\Models\Post::factory(120)-&amp;gt;create();&lt;br&gt;
    }&lt;br&gt;
}&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
As you can see we use the Post model and we say that it creates 120 records with the factory method if you use another version of Laravel the syntax may change but you can see it in the official documentation.

You may wonder what the seeders are for, the seeders are where you can insert data into your database using eloquent methods, which is the orm that Laravel has configured by default. The factories are the ones that help us generate some records with fake data in a massive way, passing only a certain number of records, as you already realized, a query builder is not used, it is only enough to indicate the fields and the value they will have.

That is why the factories are called within the database seeder, the other seeders also have to be called within the database seeder since this is the only one that is executed when we call them using the command:

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;php artisan db:seed // Seeders are executed and records will be inserted into our table&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
![data of the posts table](https://res.cloudinary.com/dwhdaxdf6/image/upload/v1647626339/Screen_Shot_2022-03-18_at_12.58.29_bfhyls.png)

Now we know what migrations, seeders and factories are for, now we will start creating our api routes and methods.


In the routes folder we have several files, as you can see we have web.php, api.php, channels and console.

We will concentrate on just the web and api, where web is for web routes and api is the one we are going to use in this tutorial.

in the api.php file we have a defined route which is the following:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Route::middleware('auth:sanctum')-&amp;gt;get('/user', function (Request $request) {&lt;br&gt;
     return $request-&amp;gt;user();&lt;br&gt;
});&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
We are going to delete this and we are going to create a route as follows:

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Route::get('/hello', function () {&lt;br&gt;
    return 'Hello World';&lt;br&gt;
});&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
As we can see, we prepend the Route class with its method, which is the verb that we will have in this route as the second parameter, we can use a callback and return a text.

Now we will test this in postman: 

To start the development server we can execute the command:

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;php artisan serve&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
![call api from postman](https://res.cloudinary.com/dwhdaxdf6/image/upload/v1647626831/Screen_Shot_2022-03-18_at_13.06.46_wdq1cg.png)

Done but now we must start creating our routes for our api, we will use versioning for our api since this way we will use a good practice and our api can grow without affecting other projects that use it.

We will create the routes, Laravel allows us to create routes together with a single line which we will do as follows:

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Route::resource('v1/posts', PostController::class)-&amp;gt;only(['index']);&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
We use resource to create several routes, but since we will only use the index method for now, we will tell it through the only function that we only want that route and so we can add the ones we need.

You will also notice that we add v1 to the endpoint of our resources, this is to be able to mutate our api quickly and safely without other apps that use it breaking in the future, for example, if we want to change the way the data is displayed or we want to remove fields from our api we would create a resource with v2 and thus we can better control how our api has changed over time

Now something very important we are going to create the controller of our posts, we already have a controller but we are not going to use it, we are going to create another controller with the command:

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;php artisan make:controller Api/V1/PostController --api&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
Ready now we have our api Controllers and versioned these are located in the app/Http/Controllers/Api folder and here we can create the v2, v3 folder as needed. 

When we created our controller we told it to be of type api with the --api flag so we will only have 5 methods unlike normal api controllers which have 7 methods.

Now we need to change the controller that we reference our route to in the api.php file:

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&amp;lt;?php&lt;/p&gt;

&lt;p&gt;use App\Http\Controllers\Api\V1\PostController;&lt;br&gt;
use Illuminate\Support\Facades\Route;&lt;/p&gt;

&lt;p&gt;Route::resource('v1/posts', PostController::class)-&amp;gt;only(['index']);&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
With doing this we have it ready now we will start creating our main endpoint

Let's see what routes we have in our laravel and what controller method is executed when we call them.

We see this with the command:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;php artisan route:list&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
![Routes](https://res.cloudinary.com/dwhdaxdf6/image/upload/v1647627648/Screen_Shot_2022-03-18_at_13.20.35_j2p63k.png)

As we can see we have a few default routes but the one that interests us is the one in position 5 as you can see it is called /api/v1/posts and as you can see it has this "Api\V1\PostController@index" this means that when we call this route will execute the index method so that is where we are going to write the logic to respond to the client.

We are going to make a call to our database and we are going to make the records come ordered and paginated, then we will return it as a response of type json.

The method would be something like this:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;public function index()&lt;br&gt;
     {&lt;br&gt;
         $posts = Post::latest()-&amp;gt;paginate();&lt;br&gt;
         return response()-&amp;gt;json($posts);&lt;br&gt;
     }&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
In this way we return the posts as json to the client so, now we will see how the data arrives from the postman:

![call api from postman](https://res.cloudinary.com/dwhdaxdf6/image/upload/v1647628003/Screen_Shot_2022-03-18_at_13.26.07_bvixmo.png) 

Ready we already have the response in a paginated way now we are going to work on our second endpoint which is the show method to show a single post according to the id of the parameters, for this we must in our api.php add another method apart from the index that this would be the show and we will change our resource method to apiResource this so that it does not create more unnecessary routes since the resource has 7 routes, this one only has 5

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Route::apiResource('v1/posts', PostController::class)-&amp;gt;only(['index', 'show']);&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
Now if we list our routes we will see a new one that is:

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;GET|HEAD api/v1/posts/{post} ........................................... ............................................ posts.show › Api\ V1\PostController@show&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
As we can see, this retains a {post}, this refers to the fact that we must pass the id of our post to be able to show the info.

So let's go to the controller to modify the show method: 

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;public function show($id)&lt;br&gt;
    {&lt;br&gt;
        //&lt;br&gt;
    }&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
First we have to look for the post in our database and then return it as a response.

We have a parameter which is the id that the user puts in the url, and thanks to eloquent and the simplicity of laravel we can do the following: 

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;public function show(Post $post)&lt;br&gt;
    {&lt;br&gt;
        return response()-&amp;gt;json($post);&lt;br&gt;
    }&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
Adding the Model as the type of the variable, Laravel understands this and gives you the record to which the model belongs.


Now let's see in postman:

![call method show from postman](https://res.cloudinary.com/dwhdaxdf6/image/upload/v1647629836/Screen_Shot_2022-03-18_at_13.56.50_j4maj5.png)

That easy we already have the show method of our api.

Now we will see the delete method. The same process we add the method to our resource in api.php and go to the destroy method in our controller.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Route::apiResource('v1/posts', PostController::class)-&amp;gt;only(['index', 'show', 'destroy']);&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
PostController : 

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;public function destroy($id)&lt;br&gt;
    {&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
Here we can do the same as in the show make Laravel bring us the record automatically: 

``` 


 public function destroy(Post $post)
    {
        $post-&amp;gt;deleted_at = now();
        $post-&amp;gt;save();
        return response()-&amp;gt;json(['message' =&amp;gt; 'Post deleted'], Response::HTTP_NO_CONTENT);
    }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;As you can see we only reassign the value of the deleted_at field with the now() function and the logical deletion is done, we do not delete it from the database. We return null and as a second parameter we pass a no content code which is 204 we can send it as a number but I prefer to use Response you can see the rest of the code in the official Laravel doc.&lt;/p&gt;

&lt;p&gt;Let's see this in the postman: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1647630433%2FScreen_Shot_2022-03-18_at_14.06.56_njmjvq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1647630433%2FScreen_Shot_2022-03-18_at_14.06.56_njmjvq.png" alt="call method destroy from postman"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we will add that in our index method only the posts that are not deleted are seen, so we will add a condition:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

  public function index()
     {
         $posts = Post::where('deleted_at', null)-&amp;gt;latest()-&amp;gt;paginate();
         return response()-&amp;gt;json($posts);
     }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In this way this method is solved and the deleted posts will no longer be shown.&lt;/p&gt;

&lt;p&gt;Now we will add that in our show method we do not want the ifno of a deleted post to be seen, so we will add an if:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

public function show(Post $post)
     {
         if ($post-&amp;gt;deleted_at) {
             return response()-&amp;gt;json(['message' =&amp;gt; 'Post have been deleted'], Response::HTTP_NOT_FOUND);
         } else {
             return response()-&amp;gt;json($post);
         }
     }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We already have solved this other method that easy.&lt;/p&gt;

&lt;p&gt;But what happens if we do the following:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1647632059%2FScreen_Shot_2022-03-18_at_14.33.42_yudz1v.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1647632059%2FScreen_Shot_2022-03-18_at_14.33.42_yudz1v.png" alt="error in found posts"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As you can see we have an html error which is not right, so how do we fix this?&lt;/p&gt;

&lt;p&gt;Whenever we consume an api in Laravel we must pass the property in the headers&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

Accept : application/json


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;With this, Laravel already knows that it should send us the error in json, so now we will obtain the following response:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1647632238%2FScreen_Shot_2022-03-18_at_14.37.08_jo3rdx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1647632238%2FScreen_Shot_2022-03-18_at_14.37.08_jo3rdx.png" alt="error not found in json"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We have a problem which is that I don't want to show this error in this way to the users so we will change the show function in this way:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

public function show($id)
     {
         try {
             $post = Post::where('deleted_at', null)-&amp;gt;findOrFail($id);
             return response()-&amp;gt;json($post);
         } catch (ModelNotFoundException $e) {
             return response()-&amp;gt;json(['message' =&amp;gt; $e-&amp;gt;getMessage()], Response::HTTP_NOT_FOUND);
         }
     }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;As you can see, we are now using the findOrFail method, this will throw us a ModelNotFoundException type exception and we will return the message with a not found code.&lt;/p&gt;

&lt;p&gt;In this way we obtain a shorter message and we do not detail the user so much for security reasons.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

{
    "message": "No query results for model [App\\Models\\Post] 1" // Post deleted
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now we can do the same in the destroy method.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

public function destroy($id)
    {
        try {
            $post = Post::where('deleted_at', null)-&amp;gt;findOrFail($id);
            $post-&amp;gt;deleted_at = now();
            $post-&amp;gt;save();
            return response()-&amp;gt;json(null, Response::HTTP_NO_CONTENT);
        } catch (ModelNotFoundException $e) {
            return response()-&amp;gt;json(['message' =&amp;gt; $e-&amp;gt;getMessage()], Response::HTTP_NOT_FOUND);
        }

    }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We are almost done, now we are going to format our responses, since we are now returning the model and this is not done in Laravel in this way. We'll do it using resources and collections.&lt;br&gt;
The resources help us to format our model and thus return the collections, they are exactly the same but it is to return collections, we see it in practice. Now we will create a resource as follows.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

php artisan make:resource V1/PostResource


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here we will also apply versioning since we can mutate these resources as our api grows. &lt;/p&gt;

&lt;p&gt;Now we go to the file app/Http/Resources/V1/PostResource: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;?php

namespace App\Http\Resources\V1;

use Illuminate\Http\Resources\Json\JsonResource;

class PostResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        return [
            'title' =&amp;gt; $this-&amp;gt;title,
            'content' =&amp;gt; $this-&amp;gt;body,
            'created_at' =&amp;gt; $this-&amp;gt;created_at,
        ];
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We make a return and assign keys and what field we want to be assigned I will leave it this way and now we are going to use it in our PostController:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

public function show($id)
     {
         try {
             $post = Post::where('deleted_at', null)-&amp;gt;findOrFail($id);
             return new PostResource($post);
         } catch (ModelNotFoundException $e) {
             return response()-&amp;gt;json(['message' =&amp;gt; $e-&amp;gt;getMessage()], Response::HTTP_NOT_FOUND);
         }
     }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here we return a new instance of the post resource remember that we can only pass one record to our resource, for several records we are going to create a collection but for this I will use a version 2 of my api and we will understand the advantages of this practice. &lt;/p&gt;

&lt;p&gt;First we will create the routes resource in api.php :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;?php

use App\Http\Controllers\Api\V1\PostController as PostControllerV1;
use App\Http\Controllers\Api\V2\PostController as PostControllerV2;
use Illuminate\Support\Facades\Route;

Route::apiResource('v1/posts', PostControllerV1::class)-&amp;gt;only(['index', 'show', 'destroy']);
Route::apiResource('v2/posts', PostControllerV2::class)-&amp;gt;only(['index']);


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;As you can see, I create the route only with the index method and I create another controller in the V2 folder of controllers and I assign an alias to it to avoid conflict in the imports, now we create the controller:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

php artisan make:controller Api/V2/PostController --api


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now we are going to do the index method just like in the PostController version 1.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

// V2/PostController
public function index()
    {
        $posts = Post::where('deleted_at', null)-&amp;gt;latest()-&amp;gt;paginate();
        return response()-&amp;gt;json($posts);
    }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Ready we have it let's see the postman:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1647633616%2FScreen_Shot_2022-03-18_at_15.00.00_sf47gn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1647633616%2FScreen_Shot_2022-03-18_at_15.00.00_sf47gn.png" alt="call v2 api method index from postman"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As you can see it is exactly the same but now in version 2 I only want to send the id and the title so for this we are going to create the collection that will help us give this a structure:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

php artisan make:resource V2/PostCollection


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now we go to the File app/Http/Resources/V2/PostCollection&lt;/p&gt;

&lt;p&gt;and we would have to do something like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

public function toArray($request)
    {
        return [
            'data' =&amp;gt; $this-&amp;gt;collection,
            'target' =&amp;gt; [
                'organization' =&amp;gt; 'com.jordan',
                'author' =&amp;gt; [
                    'name' =&amp;gt; 'Jordan',
                    'email' =&amp;gt; 'jordan@mail.com',
                ],
            ],
            'type' =&amp;gt; 'post',
        ];

    }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;As you can see, we add more information and within the data property I want it to return all the data of the collection. We use this in V2/PostController:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

// V2/PostController
public function index()
    {
        $posts = Post::where('deleted_at', null)-&amp;gt;latest()-&amp;gt;paginate();
        return new PostCollection($posts);
    }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1647633949%2FScreen_Shot_2022-03-18_at_15.05.39_fqkt8y.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1647633949%2FScreen_Shot_2022-03-18_at_15.05.39_fqkt8y.png" alt="call v2/api method index from postman"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1647633964%2FScreen_Shot_2022-03-18_at_15.05.57_tmw3ea.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1647633964%2FScreen_Shot_2022-03-18_at_15.05.57_tmw3ea.png" alt="call v2/api method index from postman"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;But we have a problem, although our structure has changed, all the post fields are still displayed. To solve this, we create a v2 resource and we will use it in our collection:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

php artisan make:resource V2/PostResource


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And we modify it:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;?php

namespace App\Http\Resources\V2;

use Illuminate\Http\Resources\Json\JsonResource;

class PostResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        return [
            'id' =&amp;gt; $this-&amp;gt;id,
            'title' =&amp;gt; $this-&amp;gt;title,
        ];
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now we have to tell our collection to use this resource:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;?php

namespace App\Http\Resources\V2;

use Illuminate\Http\Resources\Json\ResourceCollection;

class PostCollection extends ResourceCollection
{

    public $collects = PostResource::class;
    /**
     * Transform the resource collection into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        return [
            'data' =&amp;gt; $this-&amp;gt;collection,
            'target' =&amp;gt; [
                'organization' =&amp;gt; 'com.jordan',
                'author' =&amp;gt; [
                    'name' =&amp;gt; 'Jordan',
                    'email' =&amp;gt; 'jordan@mail.com',
                ],
            ],
            'type' =&amp;gt; 'post',
        ];

    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In this way we solve our problem.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1647634485%2FScreen_Shot_2022-03-18_at_15.14.29_oeeupo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1647634485%2FScreen_Shot_2022-03-18_at_15.14.29_oeeupo.png" alt="call v2/posts method index from postman"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So the applications that consume our old api will not have problems or will fall.&lt;/p&gt;

&lt;p&gt;In this way we have made an api with a few methods applying good programming practices as recommended by the laravel documentation. The challenge is that you finish the update and store methods of the api as well as the other methods of version 2.&lt;/p&gt;

&lt;p&gt;If something is not clear to you, you can comment and I will help you with pleasure.&lt;/p&gt;

&lt;p&gt;You can find the complete code in the following &lt;a href="https://github.com/jordanrjdev/apiposts" rel="noopener noreferrer"&gt;github repository&lt;/a&gt;&lt;/p&gt;

</description>
      <category>dev</category>
      <category>code</category>
      <category>laravel</category>
      <category>php</category>
    </item>
    <item>
      <title>Making a google chrome extension</title>
      <dc:creator>Jordan Jaramillo</dc:creator>
      <pubDate>Tue, 22 Feb 2022 15:10:01 +0000</pubDate>
      <link>https://dev.to/jordandev/making-a-google-chrome-extension-1j4m</link>
      <guid>https://dev.to/jordandev/making-a-google-chrome-extension-1j4m</guid>
      <description>&lt;p&gt;Today we are going to see how to make a google chrome extension and that it interacts with the dom of the current page.&lt;br&gt;
The extension is simple, it will have an input in which you can write a label and when you click the button, these elements that are on the page will be added in a red border.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The complete code can be found in this &lt;a href="https://github.com/jordanrjdev/Extension-browser" rel="noopener noreferrer"&gt;repository&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Files
&lt;/h2&gt;

&lt;p&gt;Create the following files in your project folder: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;manifest.json&lt;/li&gt;
&lt;li&gt;popup.html&lt;/li&gt;
&lt;li&gt;popup.js&lt;/li&gt;
&lt;li&gt;background.js&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Manifest.json
&lt;/h2&gt;

&lt;p&gt;Let's start by creating a &lt;code&gt;manifest.json&lt;/code&gt; file which is the one that will have the details of our extension such as (name, description) including its permissions.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

{
  "name": "Gettin started example",
  "description": "i build a example for getting started",
  "version": "1.0.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "permissions": ["storage", "activeTab", "scripting"],
  "action": {
    "default_popup": "popup.html"
  }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;first we are indicating the name description and versions, continuing with the reading we will see the property background &amp;gt; service_worker which is very important since we must register the file that will be executed in the background in this case we have a file that will be called background.js&lt;/p&gt;

&lt;p&gt;&lt;a href="https://developer.chrome.com/docs/extensions/mv3/manifest/" rel="noopener noreferrer"&gt;Here&lt;/a&gt; you can see more detailed what you can specify in your manifest.&lt;/p&gt;

&lt;h2&gt;
  
  
  Background.js
&lt;/h2&gt;

&lt;p&gt;We will create a file called &lt;code&gt;background.js&lt;/code&gt; to see how it works.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

// background.js
chrome.runtime.onInstalled.addListener(function () {
  console.log("Hello from background");
});


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Start by including a listener event for runtime.onInstalled in your background script. Inside the onInstalled listener, the extension will show a console message here we can also set persistent variables etc.&lt;/p&gt;

&lt;h2&gt;
  
  
  Load the extension in our browser
&lt;/h2&gt;

&lt;p&gt;We are going to go to the extension manager of our browser and we are going to activate the development mode. &lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1645540123%2FScreen_Shot_2022-02-22_at_09.24.48_xghrib.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1645540123%2FScreen_Shot_2022-02-22_at_09.24.48_xghrib.png" alt="Activating developer mode in my browser"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We are going to click on the button that says load unpacked and we choose the folder that has our files.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1645540123%2FScreen_Shot_2022-02-22_at_09.26.37_iq3mhh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1645540123%2FScreen_Shot_2022-02-22_at_09.26.37_iq3mhh.png" alt="load unpacked button"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We should see our extension loaded as in the image&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1645540123%2FScreen_Shot_2022-02-22_at_09.27.07_kg13z9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1645540123%2FScreen_Shot_2022-02-22_at_09.27.07_kg13z9.png" alt="Extension uploaded successfully"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we will click on the inspects view where it says service worker, a tab will open and in the console we will be able to see our message &lt;code&gt;Hello from background&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1645540124%2FScreen_Shot_2022-02-22_at_09.28.19_ghhone.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1645540124%2FScreen_Shot_2022-02-22_at_09.28.19_ghhone.png" alt="Image of our message"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Well you already have a background file where you can execute scripts in the background now we will proceed to show a form in our extension. &lt;/p&gt;

&lt;h2&gt;
  
  
  Popup.html
&lt;/h2&gt;

&lt;p&gt;As you may have already noticed, we have in our manifest a property called action: default_popup in which we indicate a file called popup.html in which we are going to put an html code with our form:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;p&amp;gt;Tag for change the border&amp;lt;/p&amp;gt;
    &amp;lt;input type="text" id="tagcolor" /&amp;gt;
    &amp;lt;button id="changeColor"&amp;gt;Change&amp;lt;/button&amp;gt;
    &amp;lt;script src="popup.js"&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We have a script which we are going to create called popup.js and that is where we are going to write the logic but let's review the content of our html which has an input and a button with their respective ids to retrieve them with js and be able to do the logic.&lt;/p&gt;

&lt;h2&gt;
  
  
  Popup.js
&lt;/h2&gt;

&lt;p&gt;In this file we are going to do several things, the first is to select our button by id&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

let changeColor = document.getElementById("changeColor");


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now we are going to add a click event to this button and in the asynchronous function we are going to select our input and thus have the value that we write.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

changeColor.addEventListener("click", async() =&amp;gt; {
   let inputtag = document.querySelector("#tagcolor");
   chrome.storage.sync.set({ inputtag: inputtag.value });

   let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

   chrome.scripting.executeScript({
     target: { tabId: tab.id },
     function: setBorderColor,
   });
});

function setBorderColor() {
   chrome.storage.sync.get("inputtag", ({ inputtag }) =&amp;gt; {
     document.querySelectorAll(inputtag).forEach((element) =&amp;gt; {
       element.style.border = "1px solid red";
     });
   });
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We will send the value of what we write in our input to our storage.sync to later access it from the setBorderColor function&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

chrome.storage.sync.set({ inputtag: inputtag.value });


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;After this we have to select the window in which we are and store it in a variable for this we use destructuring of arrays&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We will send to execute a script on the screen in which we are with the following code&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

chrome.scripting.executeScript({
     target: { tabId: tab.id },
     function: setBorderColor,
   });


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Within this setBorderColor function, the document to which we will make a selection is already the one from the tab that we indicated, it is no longer our popup.html dom, this must be clear, outside the function, the document was the equivalent to the document of the popup.html of our extension.&lt;/p&gt;

&lt;p&gt;Finally, in the setBorderColor function, what we do is obtain the persistent value that we created, which should be the name of a label, id or a class, and as a callback we will execute a querySelectorAll, we will go through the elements and change the style property. border:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

function setBorderColor() {
   chrome.storage.sync.get("inputtag", ({ inputtag }) =&amp;gt; {
     document.querySelectorAll(inputtag).forEach((element) =&amp;gt; {
       element.style.border = "1px solid red";
     });
   });
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now we are going to go to any page and we will put the name of a label in this case I will use div&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1645541590%2FScreen_Shot_2022-02-22_at_09.52.34_bgvmby.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1645541590%2FScreen_Shot_2022-02-22_at_09.52.34_bgvmby.png" alt="extension form"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Results :
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1645541590%2FScreen_Shot_2022-02-22_at_09.52.45_lsam8h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1645541590%2FScreen_Shot_2022-02-22_at_09.52.45_lsam8h.png" alt="Google"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1645541761%2FScreen_Shot_2022-02-22_at_09.55.51_q9uzfd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1645541761%2FScreen_Shot_2022-02-22_at_09.55.51_q9uzfd.png" alt="Instagram"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here, as you can see, we use various chrome tools such as storage, scripting, and tabs, which is why we define them from the beginning in our manifest.json.&lt;/p&gt;

&lt;p&gt;I hope this has really helped you now it's your turn to practice and investigate.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>html</category>
      <category>dev</category>
    </item>
    <item>
      <title>Portals in React.js with a practical example</title>
      <dc:creator>Jordan Jaramillo</dc:creator>
      <pubDate>Mon, 21 Feb 2022 18:00:59 +0000</pubDate>
      <link>https://dev.to/jordandev/portals-in-reactjs-with-a-practical-example-1id4</link>
      <guid>https://dev.to/jordandev/portals-in-reactjs-with-a-practical-example-1id4</guid>
      <description>&lt;p&gt;Portals provide a first-class option to render children into a DOM node that exists outside of the parent component's DOM hierarchy, as stated in the official React.js documentation.&lt;/p&gt;

&lt;p&gt;Portals are useful when we want to render components but our parent has a hidden overflow or a defined width and height, modals are an ideal example so we are going to build a modal from scratch and apply good user accessibility practices.&lt;/p&gt;

&lt;p&gt;You can see the complete code of the example here in this &lt;a href="https://github.com/jordanrjdev/Portals-example-react" rel="noopener noreferrer"&gt;github repository&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;First we are going to create a component which is going to be called &lt;code&gt;src/Components/Modal/index.js&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const Modal = (props) =&amp;gt; {
  let { children, close, ...rest } = props;
  if (!children) {
    children = &amp;lt;p&amp;gt;This is a example modal&amp;lt;/p&amp;gt;;
  }

  return (
      &amp;lt;div id="modal-dialog" {...rest}&amp;gt;
        &amp;lt;div className="flex flex-col justify-center items-center"&amp;gt;
          {children}
          &amp;lt;button onClick={close}&amp;gt;
            Close this modal
          &amp;lt;/button&amp;gt;
        &amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
  );
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the &lt;code&gt;src/styles.css&lt;/code&gt; file we will have the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@import url("https://fonts.googleapis.com/css2?family=Roboto:wght@300;500&amp;amp;display=swap");
* {
  font-size: 62.5%;
  font-family: "Roboto";
  margin: 0;
  padding: 0;
}

#App {
  overflow: hidden;
  height: 20vh;
  background-color: #ccc;
}

#App &amp;gt; h1 {
  font-size: 2rem;
}

div#modal-dialog {
  background-color: rgba(0, 0, 0, 0.8);
  position: fixed;
  z-index: 999;
  height: 100vh;
  width: 100vw;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

div#modal-dialog &amp;gt; div {
  background-color: #f5f5f5;
  padding: 2rem;
  border-radius: 1.2rem;
}

p {
  margin: 1.4rem 0;
  font-size: 1.5rem;
}

button {
  padding: 1rem;
  border-radius: 1rem;
  border: none;
  background-color: #9b59b6;
  color: #fff;
  cursor: pointer;
  transition: all 0.3s ease-in-out;
}

button:hover {
  background-color: #8e44ad;
}

.flex {
  display: flex;
}

.flex-col {
  flex-direction: column;
}

.flex-row {
  flex-direction: row;
}

.justify-center {
  justify-content: center;
}

.items-center {
  align-items: center;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we are going to have several styles for our modal and we have also defined some standard classes for our application.&lt;/p&gt;

&lt;p&gt;Now in the modal we will receive several &lt;em&gt;props&lt;/em&gt; such as children, close (function to close the modal) and the rest of the props that we may have, we also have a fixed element that is the button to close the modal and there we will pass the function of close on click event. &lt;/p&gt;

&lt;p&gt;We will go on to create a div in our index.html file which will be the sibling element of the parent div of our application and the file would be as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;meta charset="utf-8" /&amp;gt;
    &amp;lt;meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    /&amp;gt;
    &amp;lt;meta name="theme-color" content="#000000" /&amp;gt;
    &amp;lt;link rel="manifest" href="%PUBLIC_URL%/manifest.json" /&amp;gt;
    &amp;lt;link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" /&amp;gt;
    &amp;lt;title&amp;gt;React App&amp;lt;/title&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;noscript&amp;gt;
      You need to enable JavaScript to run this app.
    &amp;lt;/noscript&amp;gt;
    &amp;lt;div id="root"&amp;gt;&amp;lt;/div&amp;gt;
    &amp;lt;div id="modals"&amp;gt;&amp;lt;/div&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To this div we will put the id of "modals" which is in which the modal component will be injected thanks to the portals.&lt;/p&gt;

&lt;p&gt;This benefits us so that our component is not affected by the styles of our parent that has overflow hidden and height and width defined since it would not be displayed correctly.&lt;/p&gt;

&lt;p&gt;Now we will go on to create the &lt;code&gt;src/App.js&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState } from "react";
import ReactDOM from "react-dom";
import { Modal } from "./Components/Modal";
import "./styles.css";

const domElement = document.getElementById("modals");

export default function App() {
  const [stateModal, setStateModal] = useState(false);
  const openModal = () =&amp;gt; setStateModal(true);
  const closeModal = () =&amp;gt; setStateModal(false);

  return (
    &amp;lt;div id="App" className="flex flex-col justify-center items-center"&amp;gt;
      &amp;lt;h1&amp;gt;Portals Example&amp;lt;/h1&amp;gt;
      &amp;lt;div className="flex flex-col items-center justify-center"&amp;gt;
        &amp;lt;p&amp;gt;This is a div with a defined height and overflow hidden&amp;lt;/p&amp;gt;
        &amp;lt;button onClick={openModal}&amp;gt;
          Open modal
        &amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
      {stateModal &amp;amp;&amp;amp;
        ReactDOM.createPortal(
          &amp;lt;Modal close={closeModal}&amp;gt;
            &amp;lt;p&amp;gt;Modal from App.js&amp;lt;/p&amp;gt;
          &amp;lt;/Modal&amp;gt;,
          domElement
        )}
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First we have the imports and on line 6 we have a reference to the div#modal getting it with&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const domElement = document.getElementById("modals"); //Reference to div#modals for create portal
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We need to have this stored in a variable since we will need it to create the portal.&lt;/p&gt;

&lt;p&gt;Then we have the state of openModal to be able to know if the modal is open or closed, we also have the respective functions to open and close the modal. &lt;/p&gt;

&lt;p&gt;We have the button to open the modal, below this we have the most important thing which is a conditional that when the modal's state is &lt;code&gt;true&lt;/code&gt; we will use the ReactDOM createPortal function and as the first parameter we will pass the element that we want to render and how second parameter we will pass the reference of the div where we are going to inject said component so we have something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{stateModal &amp;amp;&amp;amp;
  ReactDOM.createPortal(
  &amp;lt;Modal close={closeModal}&amp;gt;
      &amp;lt;p&amp;gt;Modal from App.js&amp;lt;/p&amp;gt;
  &amp;lt;/Mode&amp;gt;,
  domElement
)}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Having this we will be able to see how the modal will be rendering inside the div#modals that is outside the parent container of our app, all this thanks to the portals and thus we had no problems with our styles or even having the modal elements separated from the dom.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1645422557%2FScreen_Shot_2022-02-21_at_00.48.40_lnenm8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdwhdaxdf6%2Fimage%2Fupload%2Fv1645422557%2FScreen_Shot_2022-02-21_at_00.48.40_lnenm8.png" alt="Imagen del dom renderizando la modal"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Improving our accessibility with good practices
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;Note:&lt;br&gt;
When working with portals, remember that managing keyboard focus is very important. For dialogs, make sure everyone can interact with them by following the &lt;a href="https://www.w3.org/TR/wai-aria-practices-1.1/#dialog_modal" rel="noopener noreferrer"&gt;WAI-ARIA Modal Creation Practices&lt;/a&gt; .&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Programmatically managing the focus.
&lt;/h3&gt;

&lt;p&gt;Our React apps continually modify the HTML DOM at runtime, sometimes causing keyboard focus to be lost or set to an unexpected element. To fix this, we need to programmatically push the keyboard focus in the correct direction. For example, resetting keyboard focus to a button that opened a modal window after that modal window is closed.&lt;/p&gt;

&lt;p&gt;Then we are going to improve our components so that there are no errors.&lt;/p&gt;

&lt;p&gt;What would happen if for some reason you have a modal to delete something and when the modal is opened the focus is sent to the confirm button, this is bad accessibility management because it can be activated inadvertently by keyboard input so it is It is always better to leave the focus on the action of closing the modal and return it to the button that activated the modal so that it does not get lost in some non-existent element of it.&lt;/p&gt;

&lt;p&gt;For this we must block the scroll and also prevent the focus from leaving our component, we will use 2 dependencies which we are going to install through:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i no-scroll focus-trap-react
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are going to improve our modal component by redirecting the focus to the cancel button and we will do this thanks to React's useRef hook. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;src/Components/Modal/index.js&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import noScroll from "no-scroll";
import { useEffect, useRef } from "react";
import FocusTrap from "focus-trap-react";
export const Modal = (props) =&amp;gt; {
  let { children, openButtonRef, close, ...rest } = props;
  if (!children) {
    children = &amp;lt;p&amp;gt;This is a example modal&amp;lt;/p&amp;gt;;
  }

  let buttonRef = useRef();

  useEffect(() =&amp;gt; {
    buttonRef ? buttonRef.current.focus() : null;
    noScroll.on();
    return () =&amp;gt; {
      openButtonRef ? openButtonRef.current.focus() : null;
      noScroll.off();
    };
  }, []);

  return (
    &amp;lt;FocusTrap&amp;gt;
      &amp;lt;div id="modal-dialog" {...rest}&amp;gt;
        &amp;lt;div className="flex flex-col justify-center items-center"&amp;gt;
          {children}
          &amp;lt;button ref={buttonRef} onClick={close}&amp;gt;
            Close this modal
          &amp;lt;/button&amp;gt;
        &amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/FocusTrap&amp;gt;
  );
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First we do the imports of our new dependencies:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import FocusTrap from "focus-trap-react";
import noScroll from "no-scroll";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we create a reference that we will use in our button &lt;code&gt;let buttonRef = useRef();&lt;/code&gt;&lt;br&gt;
and we make the reference as follows with our close button modal &lt;code&gt;&amp;lt;button ref={buttonRef} onClick={close}&amp;gt;Close this modal&amp;lt;/button&amp;gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;We will also add a new property that is the reference of our button to open our modal in order to return the focus when this modal is closed: &lt;code&gt;let { children, openButtonRef, close, ...rest } = props;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;With useRef we will know when this modal is rendered, which will indicate that it is open, we will verify that there are references to the close button, if there is a reference, we will focus it with &lt;code&gt;openButtonRef ? openButtonRef.current.focus() : null;&lt;/code&gt; and we will also block the scroll to our application with &lt;code&gt;noScroll.off()&lt;/code&gt;&lt;br&gt;
and most importantly when this component is unmounted we are going to give focus back to the button that opened the modal and we will unlock the scroll again with the following code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;openButtonRef ? openButtonRef.current.focus() : null; 
noScroll.off();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For which the useEffect would be as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   useEffect(() =&amp;gt; {
     buttonRef ? buttonRef.current.focus() : null;
     noScroll.on();
     return() =&amp;gt; {
       openButtonRef ? openButtonRef.current.focus() : null;
       noScroll.off();
     };
   }, []);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally we will wrap our modal with the component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;FocusTrap&amp;gt;
{......}
&amp;lt;/FocusTrap&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In our &lt;code&gt;src/App.js&lt;/code&gt; component we are going to create a reference to our open button and pass it to our modal so our file would look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useRef, useState } from "react";
import ReactDOM from "react-dom";
import { Modal } from "./Components/Modal";
import "./styles.css";

const domElement = document.getElementById("modals");

export default function App() {
  const [stateModal, setStateModal] = useState(false);

  let openButtonRef = useRef();

  const openModal = () =&amp;gt; setStateModal(true);
  const closeModal = () =&amp;gt; setStateModal(false);

  return (
    &amp;lt;div id="App" className="flex flex-col justify-center items-center"&amp;gt;
      &amp;lt;h1&amp;gt;Portals Example&amp;lt;/h1&amp;gt;
      &amp;lt;div className="flex flex-col items-center justify-center"&amp;gt;
        &amp;lt;p&amp;gt;This is a div with a defined height and overflow hidden&amp;lt;/p&amp;gt;
        &amp;lt;button ref={openButtonRef} onClick={openModal}&amp;gt;
          open modal
        &amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
      {stateModal &amp;amp;&amp;amp;
        ReactDOM.createPortal(
          &amp;lt;Modal close={closeModal} openButtonRef={openButtonRef}&amp;gt;
            &amp;lt;p&amp;gt;Modal from App.js&amp;lt;/p&amp;gt;
          &amp;lt;/Mode&amp;gt;,
          domElement
        )}
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this way we have applied good accessibility practices, the scroll will be blocked and also the focus will only be limited to our modal we can test using the "Tab" button, in this example we have learned about react portals and to create a modal with good practices.&lt;/p&gt;

&lt;p&gt;Now all that remains is to practice and continue investigating what we can improve on this modal component.&lt;/p&gt;

&lt;p&gt;Tell me, in what other example would you use react portals?&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>code</category>
    </item>
    <item>
      <title>Render props and render functions in React.</title>
      <dc:creator>Jordan Jaramillo</dc:creator>
      <pubDate>Fri, 18 Feb 2022 15:59:38 +0000</pubDate>
      <link>https://dev.to/jordandev/render-props-and-render-functions-in-react-342e</link>
      <guid>https://dev.to/jordandev/render-props-and-render-functions-in-react-342e</guid>
      <description>&lt;h2&gt;
  
  
  What is Render Props in React
&lt;/h2&gt;

&lt;p&gt;Render props is a pattern in react which helps us to pass the functions as a prop to the components so that we can decide the component rendering logic instead of let component render it’s own logic.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Render Functions
&lt;/h2&gt;

&lt;p&gt;Render functions (or children as functions) can provide even more flexibility and power. If you use popular React components, you've probably stumbled upon the render function technique — React-motion, Apollo-client, and React-router make excellent use of render functions to build flexible and reusable components.&lt;/p&gt;

&lt;p&gt;Render functions allow us to encapsulate logic that derives a particular state within a component and exposes that state to our parent component.&lt;/p&gt;

&lt;p&gt;Let's look at the following example. &lt;/p&gt;

&lt;p&gt;We will create a component that will obtain data from the jsonplaceholder api, this component will have different states such as: "loading, error, empty, and the render of the list of users" then we will use render props and render functions to be able to abstract the rendering logic of our component. Once explained this we can give the code.&lt;/p&gt;

&lt;p&gt;First we will create a component called list which will be reusable to render any list thanks to the render props and the render functions&lt;/p&gt;

&lt;p&gt;&lt;code&gt;List/index.js&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const List = (props) =&amp;gt; {
  const {
    loading,
    onLoading,
    error,
    onError,
    onEmpty,
    items,
    children
  } = props;
  return (
    &amp;lt;div&amp;gt;
      {loading &amp;amp;&amp;amp; onLoading()}
      {error &amp;amp;&amp;amp; !loading &amp;amp;&amp;amp; onError()}
      {items.length &amp;lt; 1 &amp;amp;&amp;amp; !loading &amp;amp;&amp;amp; onEmpty()}
      {items.length &amp;gt; 0 &amp;amp;&amp;amp; !loading &amp;amp;&amp;amp; items.map(children)}
    &amp;lt;/div&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As we can see through the props we will obtain the status of loading, error, the items and the respective functions that help us render components depending on the state as we can see we have the onError function to render a component when there is an error, onLoading when our state is loading and also onEmpty and most importantly we get the children that here is where we will take advantage of the render functions.&lt;/p&gt;

&lt;p&gt;Now we will see the App.js which is where we are going to use our List component. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;App.js&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect, useState } from "react";
import { Button } from "./Components/Button";
import { ButtonGroup } from "./Components/ButtonGroup";
import { List } from "./Components/List";
import "./styles.css";

export default function App() {
  const initialState = {
    loading: false,
    list: [],
    error: false
  };

  const [state, setState] = useState(initialState);

  const handleStatus = (nameState, valueState) =&amp;gt; {
    setState({ ...initialState, [nameState]: valueState });
  };

  const getUsers = async () =&amp;gt; {
    try {
      handleStatus("loading", true);
      const data = await fetch("https://jsonplaceholder.typicode.com/users");
      const users = await data.json();
      handleStatus("list", users);
    } catch (error) {
      handleStatus("error", true);
    }
  };

  const clearUsers = () =&amp;gt; handleStatus("list", []);
  const onLoading = () =&amp;gt; &amp;lt;p&amp;gt;Loading...&amp;lt;/p&amp;gt;;
  const onError = () =&amp;gt; &amp;lt;p&amp;gt;There was a error...&amp;lt;/p&amp;gt;;
  const renderItem = (item) =&amp;gt; &amp;lt;p key={item.id}&amp;gt;{item.name}&amp;lt;/p&amp;gt;;
  const onEmpty = () =&amp;gt; &amp;lt;p&amp;gt;Not items&amp;lt;/p&amp;gt;;

  return (
    &amp;lt;div className="App"&amp;gt;
      &amp;lt;ButtonGroup&amp;gt;
        &amp;lt;Button onClick={getUsers}&amp;gt;Fetch users&amp;lt;/Button&amp;gt;
        &amp;lt;Button onClick={clearUsers}&amp;gt;Clear users&amp;lt;/Button&amp;gt;
      &amp;lt;/ButtonGroup&amp;gt;
      &amp;lt;List
        loading={state.loading}
        error={state.error}
        onLoading={onLoading}
        onEmpty={onEmpty}
        onError={onError}
        items={state.list}
      &amp;gt;
        {renderItem}
      &amp;lt;/List&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As we can see in our app.js we have our functions which we will use as render props.&lt;/p&gt;

&lt;p&gt;First we obtain the users with a try catch depending on the result we mutate our status through the handleStatus function.&lt;/p&gt;

&lt;p&gt;Then we declare the onLoading function that what it does is render a text that says loading, the same as the onError and onEmpty functions.&lt;/p&gt;

&lt;p&gt;In the List component we pass the state and the respective functions. Thus, if we have to change the loading component, we will only have to change the onLoading function, this makes our component descriptive and we can quickly observe what the different states we have are.&lt;/p&gt;

&lt;p&gt;Now we will see the render function that helps us to render the items which is the function &lt;code&gt;const renderItem = (item) =&amp;gt; &amp;lt;p key={item.id}&amp;gt;{item.name}&amp;lt;/p&amp;gt;;&lt;/code&gt;&lt;br&gt;
This function has an item as a parameter and we render the name of this item through a paragraph and use the id as key.&lt;/p&gt;

&lt;p&gt;We pass this same function through the children of the component and then in our list we inject it into the map of our items. This is how we use our render functions, in the same way if we want to change the component of each item we can do it in the renderItem function. This is how we abstract all this render logic and can make List a component to render any list. and the components it renders depending on their states are fully customizable.&lt;/p&gt;

&lt;p&gt;Now it's a matter of practice and start making our own examples, start making our components descriptive without having to enter the component to see the code since the abstraction is applied.&lt;/p&gt;

&lt;p&gt;I leave you the complete example here:&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://codesandbox.io/embed/qngcp"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>dev</category>
      <category>code</category>
    </item>
    <item>
      <title>Cancelar peticiones con axios (ejemplo práctico con React.js)</title>
      <dc:creator>Jordan Jaramillo</dc:creator>
      <pubDate>Mon, 24 Jan 2022 15:25:07 +0000</pubDate>
      <link>https://dev.to/jordandev/cancelar-peticiones-con-axios-ejemplo-practico-con-reactjs-38d2</link>
      <guid>https://dev.to/jordandev/cancelar-peticiones-con-axios-ejemplo-practico-con-reactjs-38d2</guid>
      <description>&lt;p&gt;En el día a día como desarrolladores trabajaremos mucho con peticiones http en nuestro frontend, por eso es importante saber optimizar estas peticiones ya que si no lo hacemos podremos ocasionar perdida de memoria y esto afectará de manera negativa la experiencia del usuario. &lt;/p&gt;

&lt;p&gt;Vamos a ver un ejemplo practico para cancelar estas peticiones, para esto vamos a poner un ejemplo de uso.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const getPhotos = async () =&amp;gt; {
    try {
      onSetLoading(true);
      let rs = await getDataApi(
        "https://jsonplaceholder.typicode.com/photos"
      );
      setList(rs.data);
      onSetLoading(false);
    } catch (error) {
      console.log(error);
    }
  };

useEffect(() =&amp;gt; {
    getPhotos();
  }, []);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Imagina que un usuario quiere obtener cierta data de nuestra aplicación y accede a la pantalla que llama a esta data, pero por alguna razón el usuario vuelve al menú o simplemente le da atrás en el navegador antes de que la petición se resuelva pues si vemos este caso mas detallado veremos que la petición que hicimos no se cancela automáticamente como podemos ver en el ejemplo no estamos limpiando nuestro componente por lo que veremos como hacerlo. &lt;/p&gt;

&lt;h2&gt;
  
  
  Función para obtener data
&lt;/h2&gt;

&lt;p&gt;Crearemos una función global para hacer nuestras peticiones tipo get&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import axios from "axios";

export const getDataApi = async (url, cancelToken = null) =&amp;gt; {
  if (!url || !url.trim()) throw new Error("The endpoint is required");
  return axios.get(url, cancelToken &amp;amp;&amp;amp; { cancelToken: cancelToken.token });
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Como ya pudiste observar tenemos la función &lt;code&gt;getDataApi&lt;/code&gt; esta recibe la url y un cancel token que puede ser enviado como no y realica su respectiva validacion antes de enviarlo a la configuración de la petición. Podemos hacer que sea obligatorio para asi no olvidar de que debe estar allí (sería una buena practica hacerlo).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const Photos = (props) =&amp;gt; {
  const [list, setList] = useState([]);
  const { loading, onSetLoading, onLoading, onBack } = props;

  const getPhotos = async (source = null) =&amp;gt; {
    try {
      onSetLoading(true);
      let rs = await getDataApi(
        "https://jsonplaceholder.typicode.com/photos",
        source
      );
      setList(rs.data);
      onSetLoading(false);
    } catch (error) {
      console.log(error);
    }
  };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  Función que se encargará de realizar la petición a la api
&lt;/h1&gt;

&lt;p&gt;Ahora vamos a crear una función que se encargue de llamar a nuestra api&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const Photos = (props) =&amp;gt; {
  const [list, setList] = useState([]);
  const { loading, onSetLoading, onLoading, onBack } = props;

  const getPhotos = async (source = null) =&amp;gt; {
    try {
      onSetLoading(true);
      let rs = await getDataApi(
        "https://jsonplaceholder.typicode.com/photos",
        source
      );
      setList(rs.data);
      onSetLoading(false);
    } catch (error) {
      console.log(error);
    }
  };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Como puedes ver esta recibe como parametro un source el cual puede ser obviado y este se lo enviamos como segundo parametro a la función &lt;code&gt;getDataApi&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Ahora que tenemos esto claro veremos como llamariamos esta función en nuestra primera carga del componente.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; useEffect(() =&amp;gt; {
    const CancelToken = axios.CancelToken;
    const source = CancelToken.source();
    getPhotos(source);
    return () =&amp;gt; {
      source.cancel("Canceled");
    };
  }, []);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;En este useEffect tenemos la creación de nuestro cancel token y se lo enviamos a la funcion &lt;code&gt;getPhotos&lt;/code&gt; para tener la referencia de cual es la peticion que se va a cancelar. &lt;/p&gt;

&lt;p&gt;Al limpiar nuestro componente podemos hacer un source.cancel y enviar un mensaje personalizado para manejo de errores etc. &lt;/p&gt;

&lt;p&gt;No necesitas crear un cancel token para varias peticiones veamos un ejemplo:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;useEffect(() =&amp;gt; {
    const CancelToken = axios.CancelToken;
    const source = CancelToken.source();
    getPhotos(source);
    getDateUser(source);
    getMusics(source);
    return () =&amp;gt; {
      source.cancel("Canceled");
    };
  }, []);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;En este caso podemos ver que al limpiar nuestro componente se cancelarán todas las peticiones que esten pendientes. &lt;br&gt;
Tambien podemos hacer una limpieza de nuestro estado. &lt;/p&gt;

&lt;p&gt;De esta manera ya sabemos como cancelar nuestras peticiones y reducir la posibilidad de tener memory leak en nuestra aplicación. &lt;/p&gt;

&lt;p&gt;Ahora para probar nuestro ejemplo te dejo el código completo, te recomiendo que el ejemplo lo pruebes en una pestaña en blanco y en la opción de network del navegador selecciones el preset de slow 3G para que así puedas ver como la petición se cancela.&lt;/p&gt;

&lt;p&gt;Ejemplo completo : &lt;br&gt;
&lt;iframe src="https://codesandbox.io/embed/2cfmd"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

</description>
      <category>react</category>
      <category>axios</category>
      <category>javascript</category>
      <category>http</category>
    </item>
  </channel>
</rss>
