TypeError: uuidv4 is not a function

Viewed 6134

I'm getting this TypeError in my code can someone plz help me there seems to be an issue in line 22 to 25. This code is related to printing a todo list. In this section of code I assign the name to lists. Also on visual studio code the files are compiling without any errors whereas when I start npm this error shows up in the browser.

'''

import React, { Component } from 'react';
import List from './List.js';
const uuidv4 = require('uuid');

class Lists extends Component {

  render() {
    // If there are no lists, display a relevant message
    if(this.props.lists.length === 0) {
      return (
        <div id="listsDiv" className="List">
          <h2>Add new lists to get started!</h2>
        </div>
      );
    }

    // Otherwise, for each list, create a div
    var items = this.props.items;
    var lists = this.props.lists;
    var addItem = this.props.addItem;
    return (
      <div key={uuidv4()}>
      {lists.map(function(listName) {
        return (
          <List name={listName} items={items[listName]} addItem={addItem.bind(this)} key={uuidv4()} />
        )
      })}
      </div>
    );
  }
}

export default Lists;

'''

2 Answers

You need to import v4 as uuidv4:

import { v4 as uuidv4 } from "uuid";

or

const { v4: uuidv4 } = require('uuid');

uuid has different options to generate id's like v1, v3, v4, etc. As you want to generate a v4 id. You can use it this way.

<div key={uuidv4.v4()}></div>

Note: I suggest you to import it as.It will be easy to understand.

const uuid = require('uuid')    
Related