teleren/devto huggingface dataset:
3 Reasons to useReducer() over useState()
Tags: react, usereducer
Published: 2019-08-18 20:35:47



## What It Is

`useReducer()` is a method from the React Hooks API, similar to `useState` but gives you more control to manage the state. It takes a reducer function and initial state as arguments and returns the state and dispatch method:
```javascript
const [state, dispatch] = React.useReducer(reducerFn, initialState, initFn);
```
A reducer (being called that because of the function type you would pass to an array method`Array.prototype.reduce(reducer, initialValue)`) is a pattern taken from the Redux.  If you are not familiar with Redux, in short, a reducer is a pure function that takes previous state and action as an argument, and returns the next state. 
```javascript
(prevState, action) => newState
```
Actions are a piece of information that describes what happened, and based on that information, the reducer specifies how the state should change. Actions are passed through the `dispatch(action)` method.

## 3 Reasons to Use It

Most of the time, you are well covered with just `useState()` method, which is built on top of `useReducer()`. But there cases when `useReducer()` is preferable.

### Next state depends on the previous
It is always better to use this method when the state depends on the previous one. It will give you a more predictable state transition. The simple example would be:
```javascript
function reducer(state, action) {
  switch (action.type) {
    case 'ADD': return { count: state.count + 1 };
    case 'SUB': return { count: state.count - 1 };
    default: return state;
  }
}

function Counter() {
  const [state, dispatch] = React.useReducer(reducer, { count: 0 });
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'ADD'})}>Add</button>
      <button onClick={() => dispatch({type: 'SUB'})}>Substract</button>
    </>
  );
}
```

### Complex state shape
When the state consists of more than primitive values, like nested object or arrays. For example:
```javascript
const [state, dispatch] = React.useReducer(
  fetchUsersReducer,
  {
    users: [
      { name: 'John', subscribred: false },
      { name: 'Jane', subscribred: true },
    ],
    loading: false,
    error: false,
  },
);
```
It is easier to manage this local state, because the parameters depends from each other and the all the logic could be encapsulated into one reducer.

### Easy to test
Reducers are pure functions, and this means they have no side effects and must return the same outcome given the same arguments. It is easier to test them because they do not depend on React. Let's take a reducer from the counter example and test it with a mock state:
```javascript
test("increments the count by one", () => {
  const newState = reducer({ count: 0 }, { type: "ADD" });
  expect(newState.count).toBe(1)
})
```

## Conclusion
`useReducer()` is an alternative to `useState()` which gives you more control over the state management and can make testing easier. All the cases can be done with `useState()` method, so in conclusion, use the method that you are comfortable with, and it is easier to understand for you and colleagues.
I Did Something Scary
Tags: python, motivation, mentalhealth, tutorial
Published: 2019-08-18 19:58:49

If you know me, you know I've been [blogging about code](https://therenegadecoder/com) since late 2016. Since then, I graduated college, started working in the industry, and ultimately transitioned into a PhD program. Now, I'm just days away from my qualifying exam, and I'm burnt out. To cope with the stress, I decided to do something scary: I made a YouTube video.

{% youtube k1lE5QxNAM4 %}

As an introvert, this is something that I've avoided for a long time. After all, I'd much rather be sitting in front of a keyboard and typing away. But after a year of teaching, I thought I could try transitioning those skills into videos.

To be honest, I had a lot of fun with this. It's surprising what you can do with a webcam these days. At any rate, thanks for stopping by! I appreciate it.
Apache Camel #3 - RabbitMq
Tags: java, rabbitmq, apache, camel
Published: 2019-08-18 18:58:46

---
title: Apache Camel #3 - RabbitMq
published: true
description: Connecting and using RabitMq
tags: #java #rabbitmq #apache #camel
cover_image: https://thepracticaldev.s3.amazonaws.com/i/4y77w0gtvru6d7wv7yv9.jpeg
---

Hello there again!

It passed 2 months since my last article, so I decided to write a new one.

Today we will focus on RabbitMq and what we can do with it using Camel.

<h3>Dependencies</h3>

<a href="https://mvnrepository.com/artifact/org.apache.camel/camel-rabbitmq">Maven repository -> Camel RabbitMq</a>


<h3>Connection to RabbitMq</h3>

When using SpringBoot:

1. Create a class with @Configuration annotation.
2. Create a method which will return ConnectionFactory and annotate it with @Bean.
3. Instance a connection factory and set properties. 

<div class="highlight">
    @Bean
    public ConnectionFactory rabbitConnectionFactory() {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost);
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("Username");
        connectionFactory.setPassword("Password);

        return connectionFactory;
    }
</div>

*note: You can use application properties to connect to the server. 

If you are using pure Camel:

<img src="https://thepracticaldev.s3.amazonaws.com/i/zlluic9su8pvb8isxkbp.png" />

<h3>Using RabbitMq</h3>

Now that we successfully connected to RabbitMq it's time to start consuming/producing messages to queue/exchange.

<a href="https://camel.apache.org/staging/components/latest/rabbitmq-component.html">Camel RabbitMq component documentation.</a>

Consuming Message from the queue:

1. We will set the rabbitMq component to fetch from the queue which is bind to exchange.
2. Log message body received.

<div class="highlight">
public void configure() {

    from("rabbitmq:exchangeA?queue=QueueA&declare=true")
    .routeId("RabbiqMqConsumer")
    .log("Message received: ${body}");
</div>

Producing Message to exchange:

1. We will create a route.
2. Set message body.
3. Send a message to the exchange.

<div class="highlight">
public void configure() {

     from("timer:fooo?period=10000")
     .routeId("RabbiqMqProducer)
     .setBody().constant("{\"foo\":\"bar\"}")
     .log("Message to be sent: ${body}")
     .to("rabbitmq:exchangeB");
  
</div>

Aand that's all folks, if anyone have some question, feel free to ask me via DM or just leave a comment.

<img src="https://media.giphy.com/media/2PuVOnv02rRvy/giphy.gif" />
Deploying a project with Laravel Vapor
Tags: serverless, laravel, beginners, web
Published: 2019-08-18 18:29:40

---
title: Deploying a project with Laravel Vapor
published: true
description: Find out how easy it is to deploy your Laravel projects with the new serverless offering from Laravel: Vapor.
tags: serverless,laravel,beginner,web
cover_image: https://owenconti.com/static/images/deploying-a-project-with-laravel-vapor.jpg
canonical_url: https://owenconti.com/laravel/deploying-a-project-with-laravel-vapor/
---

Deploying your Laravel projects is now as simple as running two commands on your command line.

Find out how easy it is to up and running with Laravel Vapor:

{% youtube TOalV_Mu9Fg %}
Using the Switch Statement with Logical Operators
Tags: javascript, beginners, flatiron, explainlikeimfive
Published: 2019-08-18 17:58:22

JavaScript's switch statement is a pretty powerful tool, but one I've generally avoided because it's not as predictable as if statements or the ternary operator. But while working through [Codesmith's CSX challenges](https://csx.codesmith.io/), I set my mind to using switch for one of the problems and learned something interesting in the process.

####This is the challenge:
```txt
Create a function gradeCalculator which takes a grade (number) and returns its 
letter grade.

grades 90 and above should return "A"
grades 80 to 89 should return "B"
grades 70 to 79 should return "C"
grades 60 to 69 should return "D"
59 and below should return "F"
```
####Below is my initial solution:
```javascript
function gradeCalculator(grade) {
  switch (grade) {
    case (grade >= 90):
      return "A"
    case grade >= 80:
      return "B"
    case grade >= 70:
      return "C"
    case grade >= 60:
      return "D"
    case grade <= 59:
      return "F"
  }
}
```
Can you spot the mistake? At first, I couldn't understand why the terminal returned
```txt
undefined
undefined
undefined
undefined
undefined
```
But a quick Google search brought me to a StackOverflow discussion that addressed the issue. 

####The Answer
Basically, JavaScript is trying to compare the expression in the parentheses to the values of the cases.

If `grade = 92`, `grade >= 90:` would return `true`, but I had my switch statement to comparing `true` to grade (or 92). True === 92 returns undefined

####The proper way to formulate my switch statement is:
```javascript
function gradeCalculator(grade) {
  switch (true) {
    case (grade >= 90):
      return "A"
    case grade >= 80:
      return "B"
    case grade >= 70:
      return "C"
    case grade >= 60:
      return "D"
    case grade <= 59:
      return "F"
  }
}
```

Check out the StackOverflow discussion [here](https://stackoverflow.com/questions/2312817/javascript-switch-with-logical-operators).
Help with basic code
Tags: discuss
Published: 2019-08-18 16:12:24

Hello,

I'm want to build a tool for my friends that lets us programmatically fill in a google form. The standard google form website is fine, but I want to build my own site that sends the info.

So I will need to have a website that people can go to, that will do things like collect the date, perform some string manipulation and then send a POST request to google. http://topslotreviews.com/casino-reviews/

Right now I can do this all from my command line using curl/libcurl but I want to make a version that is easy for my friends to use.

I'm not really sure if this can be done hosting a static website and then processing on the user's computer or if my web hosting service will need to run some kind of code.

Any advice?
Simplifying Processes before Automation
Tags: devops, productivity, automation, processess
Published: 2019-08-18 15:52:37

My manager recently came to me and dropped an automation project on my lap (Yaaay!!). Without any context of the issues, the expectations of the project or any planning, the request was something I have seen many times over the years. 

With the rise in the awareness of DevOps roles more than DevOps practices, this pattern is common these days. Hire a "DevOps", give him the task to "automate the world" and you will have CI/CD... eventually.

Wrong! You will have your processes automated, but if they were a mess to begin with, you just added another team and more tools and code, to the mix. Automation is an enhancement to processes not a replacement of them.

Let's take application configuration as an example. Using key management tools like vault and integrating them into your pipeline, you automate the configuration push to your application. Amazing!!! You just saved 10 minutes per deployment. But what about the underlying process? Configuration generation, secure sharing and tracking changes to it. You know, the process that takes days and several tickets across multiple teams to achieve.

Most teams do not focus on these "pre-deployment" processes since their visibility is low, so the impact is hidden. That is, until something goes wrong. Now you need to rollback but you didn't track the changes. You need to update the values, but you are not the one who generated them.  And you need to do all this within a tight SLA and following all the requisite security protocols. 

In short, the wrong problem was solved. And with the rise in the popularity of the micro-service architecture, the scale of this issue can be enormous (Recently worked with 76 different micro-services, configuration management was a nightmare until we adopted [ConfigTree](https://configtree.co/)).

Processes are what need to be fixed, automations can always be developed and enhanced. The primary focus of any "DevOps Team" should not be the introduction of automated builds or CI/CD, but the re-engineering of the underlying processes. 

The path to achieving the DevOps Transformation, does not start in code. It starts on a white board and is almost always a mess!!!
WebStorage APIs and it's uses in day to day coding
Tags: htmlwebstorage, localstorage, html
Published: 2019-08-18 15:24:36

Web storage APIs are used to store data in the browser. Using web storage API we can store a minimum of 5MB data in desktop browsers.There is 2 mechanisms that are most commonly used in the modern web development world are **Local storage** and **Session storage**.

Why we should use Web storage?

- To store user's specific data in their own browsers such as navigation history, Profile details and other data that are irrelevant to store in the server's database.
  
- Some user's specific data loading from the server via API call may be very expensive in terms of time.

Let's dive into details 

## LocalStorage

In this web storage, we can store data in a key-value pair format.
Data stored in the web browser and data will persist even if the browser is closed. Data will remain as it unless and until we forcefully clear the data. We can store minimum of 5 MB or higher based on browser and platform.

### Methods

Local storage has various methods to access, store, update and delete the data.

To save the data

    window.localStorage.setItem("name","John Doe") 

access the data 

    window.localStorage.getItem("name") //Output John Doe

remove the data from local storage

    window.localStorage.removeItem("name") //Removes the data 


update the data 

    window.localStorage("name","Nicolas")

To store the JSON data in local storage, We have to first convert JSON data into a string and then store it as localStorage accepts only string data.

    let userData=JSON.stringify({"name":"Nicolas","email_id":"nicolas@abc.com"});
    window.localStorage.setItem("userData",userData);

To access the data, Again we have to convert a string into JSON data

    let userData=window.localStorage.getItem("userData");
    console.log(JSON.parse(userData));

## SessionStorage

sessionStorage is the same as localStorage except data will be available until the browser tab is closed. Data will be available in a particular session. It also can store a minimum of 5 MB data. 

### Methods

To save the data

    window.sessionStorage.setItem("name","John Doe") 

access the data 

    window.sessionStorage.getItem("name") //Output John Doe

remove the data from local storage

    window.sessionStorage.removeItem("name") //Removes the data 

This web storage API also accepts string data only.
What is the best course you have ever taken from MOOC?
Tags: discuss, career, computerscience, programming
Published: 2019-08-18 14:59:37

---
title: What is the best course you have ever taken from MOOC?
published: true
description: 
tags: discuss, career, computerscience, programming
---

It's a great question to find some hidden gems!

Personally, I prefer taking courses on [edX](https://www.edx.org/). 

In my opinion, it is one of the best online sources of learning out there, speaking from experience.

Many prestigious and well-known institutes such as MIT, Harvard, Berkeley, etc. worked and keep working collectively to provide high-quality material (lectures, labs, assignments) with each course having an exceptional community which will be present at all times to guide you and answer your questions.

Also, there are many inspiring stories of learners from around the world, who have spent time taking courses on edX.

Whatever platform or class you take, just remember that you get out of it only what you put in. You cannot learn by observing - you need to jump in and engage deeply with the content. Enjoy!

___

*Don't miss my new newsletter issue on Monday, get it first [here](https://www.ilonacodes.com/networking-cheat-sheet/)*
Why start a blog?
Tags: blog, writing, sharing, community
Published: 2019-08-18 14:50:34

---
title: Why start a blog?
published: true
description: Entering the blogosphere.
tags: blog, writing, sharing, community
cover_image: https://raw.githubusercontent.com/RonanDConnolly/personal-gatsby/ronanc/static/images/why-start-a-blog.png
---

## Previous attempts

I've tried this blogging thing here and there over the years.
Usually, I would end up blogging about a variety of things: food, nature, technology, poetry, etc.
To be honest, this is probably why I didn't continue, it wasn't niche enough.

Now that I've read enough blogs, I have a better idea of how to do my own.
My niche is Front-End software development, and this is what I will be blogging about.

I'll leave my business and finance knowledge to separate blogs if I wish to write articles on them.

## Why create a blog?

I want to use this blog as a learning tool. Everything I blog about will be something I've just learned.
The great thing about this is that I'll be writing in a way that is beginner-friendly. Once a concept has clicked for me, I'll summarize my learnings for you to digest.

As such there may be errors in my articles, and if there are and people point it out, that's great. I can then learn from my audience!

## What to blog about?

I'll be covering the niche of Front-End software engineering.
This will cover:

- Vanilla JS
- Angular & everything within (RxJS, TS, AgGrid, Sass, etc)
- Productivity tips
- Getting a job
- Digital nomadism
- Tools, techniques, and workflows
- UI Design

## Audience

I'm aiming this at the Front-End community and will be sharing on Dev, Twitter, LinkedIn, and my personal site (https://ronanconnolly.dev/blog).

To be honest, I'm writing this for myself, and if others learn from it that's great!

But I am very excited to see what this Dev.to community is all about ☺️
What I Learned From Bombing An Amazon Coding Assessment
Tags: career, amazon, beginners, interview
Published: 2019-08-18 14:49:35

Recently, I was invited to take an online coding assessment with Amazon. As I'm contracted with my current job for a while yet, I thought it might be fun just to try it out, with no pressure. Here's what I learned from absolutely crashing and burning on that coding assessment:

## \#1. Solve the Problem First

I spent a good chunk of my time validating arguments, which -- while this may be what you'd do in real life -- is not a good idea for a coding assessment. Sometimes, companies will throw in edge cases -- maybe your `List` is empty, or is `null` -- but usually that's after they verify the behaviour of your solution on valid inputs.

## \#2. Know the Basics

You don't want to have to waste time Googling how to deep copy an array when the timer is counting down. Know how to work with all of your standard data structures and practice, practice, practice.

## \#3. Read the Prompt Carefully

There will sometimes be caveats to your prompts. Maybe the prompt wants you to return an optimal solution if it exists, but if your solution falls below some threshold, don't return anything at all. Make sure you're satisfying the requirements of the prompt.

## \#4. Use Your Own Editor

Online coding assessments more or less have to provide an online IDE of sorts to help you compile, debug, and run your programs. __Don't use it.__ It will be unfamiliar, slow, and it may have particular features you don't want (code completion), or be missing some that you do (automatic library imports).

## \#5. Practice with Restricted Time

These coding assessments are meant to be quick, but not so quick that you run out of time if you know what you're doing. That being said, when you're finished, you'll probably want to go back and clean some code, optimise, and add some comments. Practice with _less_ time than you're supposed to be allotted.

There are [third party](https://coderbyte.com/) assessment platforms, and Amazon has a [coding assessment demo](https://www.myamcat.com/start-demo?data=VvSY8gb%2BBAAefK0phJWENBOPoTXDc8na4fhRROtwuZ9MIbQ7gXB2pLYyDf%2B4UUy3bjNJmcgRqJuzDgML1nQF%2Bg%3D%3D) available online. I'm sure these exist for other companies, if anyone can provide them in the comments.

---

That's it! I think if I had followed my own advice above, I might have at least been able to finish the prompts in time. If you're a perfectionist like me, you'll need to leave that at the door to be able to first make a solution that works, and then go back and clean it up. Good luck!

If you enjoyed this post, please consider supporting my work by <a href='https://ko-fi.com/Z8Z811E9B'>buying me a coffee</a>!
Growing as a Developer - Advice from Dan Heller
Tags: career, motivation, beginners, management
Published: 2019-08-18 14:22:09

At Uber, my colleague, [Dan Heller](https://medium.com/@daniel.heller) is a developer who moved to being an engineering manager, then back to his roots as a developer. He wrote up advice that he would have given himself when he started his career as a software engineer. He shared this as advice for people on his team. It went viral within the company and after many requests to do so, he also [shared it online](https://medium.com/@daniel.heller/ten-principles-for-growth-69015e08c35b).

His advice is something I still frequently refer to for new starts on my team, as well as when people ask me for tips on how to grow to be a great engineer. **This advice is evergreen for anyone starting work at a tech company, a startup or working as part of a team**, within a larger organization. I also could not agree more with the advice on writing: [writing well is one of the very much undervalued skills for developers](https://blog.pragmaticengineer.com/on-writing-well/).

**[Read his ten principles for growth as a software engineer here](https://medium.com/@daniel.heller/ten-principles-for-growth-69015e08c35b)** and you can follow [Dan Heller](https://medium.com/@daniel.heller) on Medium.

---

_About me:_ I'm an engineer turned engineering manager, working at the intersection of Silicon Valley & European startups and tech companies. Follow me here and [on Twitter](https://twitter.com/GergelyOrosz). I write longer essays on software engineering on my blog, [The Pragmatic Engineer](https://blog.pragmaticengineer.com/). I also send a [monthly newsletter](https://blog.pragmaticengineer.com/newsletter/) with extended notes on software engineering and tech leadership topics.
Do you "Really" know JavaScript?
Tags: javascript, node, react
Published: 2019-08-18 12:52:18

#JavaScript?
JavaScript is one of the biggest growing programming languages to code on the web. But do you really know JavaScript?

For Example:
``` javascript
var a = "42";
var b = 42; 
a == b;			// true
a === b;		// false
```

![alt-text](https://media.giphy.com/media/aWPGuTlDqq2yc/giphy.gif)

Wondering why? or for some who might now, have you wondered how much you don't know about JavaScript.

Most People will be shocked too see how useful it can be to learn more about plain JavaScript/ES6+. Yes, even if your using a big time JS framework like Node or React its gonna be a waste without good foundation of the basics.  

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/pzhugwpu705obrombr18.jpg)

>`Object Destructing, Generators, this object; async , parallel, and concurrent functions`

and the List goes on, these are only the basics. If you wanna up your JS game then Go **BACK TO THE FOUNDATION** , give [YDKJS](https://github.com/getify/You-Dont-Know-JS) (its a free ebook repo) a read and there are many more resources to know about and also go deep into ES6 and the latest features JS is always updated to make your life better no harm in knowing how.

#Conclusion

JavaScript is always evolving and faster then you can think of, keep looking into these new features and how they improve performance and not just for info but to know what all your JS code means and how you can improve on it!