🔥 Vue Tips #25: Reduce, reuse, recursion?
Tags: vue, webdev, javascript, tutorial
Published: 2021-09-09 12:24:40

---
title: "🔥 Vue Tips #25: Reduce, reuse, recursion?"
published: true
description: "Simpler testing, reducing objects, Vuex for React, and so many conferences."
canonical_url: https://michaelnthiessen.com/weekly-025-september-8/
tags: vue, webdev, javascript, tutorial
series: Vue Tips
---

_This newsletter was sent out to my list on September 8, 2021. [Sign up here](https://michaelnthiessen.com/newsletter) to get emails like this each week!_


Hey there,

Today we're talking reduce, dependency injection, React (don't worry, this is still a Vue newsletter), code comments, and conferences.

But you don't have to take my word for it.

And just to keep you in the loop: right now there's a [35% off sale happening for Clean Components](https://michaelnthiessen.com/clean-components). It ends September 13 at midnight (EDT).

— Michael


## 🔥 Simpler testing with dependency injection

Jest makes it easy to mock or stub out functions, but you can also use dependency injection to make things easy to stub:

```js
export default {
  props: {
    // Returns text to be displayed
    someMethod: {
      type: Function,
      required: true,
    },
  },
};
```
```js
it('should work', () => {
  const { getByText } = render(MyComponent, {
    props: {
      someMethod() {
        return 'Test text';
      },
    },
  });
  getByText(/Test text/);
});
```

If it's coming from outside of the component, it's pretty straightforward to stub it out or mock it however you need, in order to get the test to do what you want.

You can do this in a variety of ways, depending on your use case:
- props
- provide/inject
- Vuex
- custom plugin

(There are probably many more)


## 🔥 Reducing Objects
The `reduce` function is really great for converting arrays into objects, but it can be intimidating.

If we have a bunch of items that all have an `id`:
```js
{
  id,
  //...
}
```

We can reorganize the array into an object, where the key for each item is the item's `id`:
```js
const obj = arr.reduce((prev, next) => {
  // Grab the id from the item
  const { id } = next;

  // Add the item to our object
  prev[id] = next;

  // Return the object so we can add more items
  return prev;
}, {});
```

You get an object that looks like this:
```js
{
  'id1': { id: 'id1', ... },
  'id2': { id: 'id2', ... },
  'id3': { id: 'id3', ... },
}
```

If you want to group all objects in an array by a specific property, you can do something very similar:
```js
const obj = arr.reduce((prev, next) => {
  // Grab the property from the item that we want to group by
  const { prop } = next;

  // Add a new array to the object if this is the first one
  // with this value
  if (prev[prop] === undefined) {
    prev[prop] = [];
  }

  // Add our item to this array
  prev[prop].push(next);

  // Return the object so we can add more items
  return prev;
}, {});
```

Our final object looks like this:
```js
{
  'prop1': [
    { prop: 'prop1', ... },
    { prop: 'prop1', ... },
    { prop: 'prop1', ... },
  ],
  'prop2': [
    { prop: 'prop2', ... },
    { prop: 'prop2', ... },
    { prop: 'prop2', ... },
  ],
}
```

## 🔗 (Sponsored) Keep on top of new tech with DevTrends.io

It seems that every week there's a new JS framework, or a new and better way to write CSS (which is just the old way again).

Just as you get comfortable writing unit tests you learn that integration tests are actually the way to go. Oh, and the way you've been writing your tests is completely wrong.

Ugh 🤦‍♂️

It would be so much simpler if we could ignore everything, but hidden among all these new tools are amazing gems that can transform the way we work.

But keeping up with all of them is impossible.

**That's why my long time friend, Anthony Gore (who also created Vue.js Developers), created DevTrends.io**

He does all of the research on new tech and tools for you, and then teaches you the most important details in short, informative videos.

[Click here to check out some recent videos](https://devtrends.io/)


## 📜 Vuex — but for React
This is an interesting short read on writing a Vuex clone, but in React.

I've taken lots of ideas from React and used them in Vue over the years, but haven't seen many people take ideas from the Vue ecosystem yet.

What patterns or ideas can you borrow from other frameworks or languages you've used in the past?

Read it here: [I wrote Vuex — but for React!](https://itnext.io/i-wrote-vuex-but-for-react-the-challenges-i-faced-and-where-you-can-get-it-d465985d8a5)


## 🗞 News: It's conference season!

Yes, I'm just copying and pasting this section each week.

But you know what? I don't want you to forget about a great conference — like Nuxt Nation, which is happening _next week_.

We have _four_ incredible conferences coming up in the next 2 months, all accessible online and two offering (limited) in-person experiences:
- [Nuxt Nation](https://nuxtnation.com/) — September 15th — free and online
- [Vuejs Global (Amsterdam)](https://www.vuejs.amsterdam/) — October 1st and 4th — Amsterdam and online
- [Vue.js Conference (London)](https://vuejs.london/) — October 20-21 — London and online
- [VueConf Toronto](https://www.vuetoronto.com/) — November 22-23 — free + online


## 💬 Comments
"Good code is its own best documentation. As you're about to add a comment, ask yourself, 'How can I improve the code so that this comment isn't needed?'" — Steve McConnell


## 🧠 Spaced-repetition: Define multiple components in a single file

__The best way to commit something to long-term memory is to periodically review it, gradually increasing the time between reviews 👨‍🔬__

__Actually remembering these tips is much more useful than just a quick distraction, so here's a tip from a couple weeks ago to jog your memory.__

Every now and then you just need a small component, one that's not worth an entirely new file:
```js
// A small, secondary component
const SmallComponent = {
  // Create a component like you normally would
  data() {
    //...
  },
  computedProps: {
    //...
  },

  // Use the template property instead of a template block
  template: `
    <div>Hello!</div>
  `
};

// Your main component
export default {
  components: { SmallComponent },
  // ...
};
```

This is perfect for reusing code within a component, where a `v-for` doesn't work.

However, if the code is more complex or is likely to be used by other components, making a proper [reusable component](https://michaelnthiessen.com/reusable-components) is the best way to go.

Note: You can get proper syntax highlighting of the HTML string using [this VSCode extension](https://marketplace.visualstudio.com/items?itemName=Tobermory.es6-string-html).


## Exclusive tips and insights every week

Join 8135 other Vue devs and [get exclusive tips and insights](michaelnthiessen.com/newsletter) like these delivered straight to your inbox, every week.

> You have great content in your emails. I seriously learn something from every one of them. — Titus Decali

> Thanks for another beautiful tip 🙏 — Victor Onuoha

> Loving these, and the spaced repetition — Mark Goldstein

[Sign up here](michaelnthiessen.com/newsletter)