Search code examples
javascriptreactjslodashcreate-react-app

Using Lodash with create-react-app results in "Uncaught TypeError: _this.reduce is not a function"


I'm new to React and create-react-app and I'm attempting to use Lodash in my App.js file and I'm running into an error. Uncaught TypeError: _this.reduce is not a function. I've added

import _ from 'lodash';
import shuffle from 'lodash/shuffle';
import random from 'lodash/random';
import find from 'lodash/find';

to the top of my App.js and

import Lodash from 'lodash';

in my index.js file.

For testing I've used this reduce example from MDN, which works:

  var total = [0, 1, 2, 3].reduce(function(sum, value) {
    return sum + value;
  }, 0);

But the line that uses lodash throws the error above:

  var books = _.shuffle(this.reduce((p, c, i) => {
    return p.concat(c.books);
  }, [])).slice(0, 4);

In this case this is an array like this:

var data = [
  {
    name: 'Mark Twain',
    imageUrl: 'images/authors/marktwain.jpg',
    books: ['The Adventures of Huckleberry Finn']
  }
];

Solution

  • As per the comments section, your this reference is not pointing to what you expect.

    Change it to data and it should work.