Problems with Item Types in react dnd (Invariant Violation: item type must be defined)

10.1k views Asked by At

i'm trying to define the Item Type when i drag a item on my own way. But somehting goes wrong if i do it that way and drag the item, it shows me "Invariant Violation: item type must be defined" after droping the item. That means i have a file with ItemTypes where i define everything:

export const ItemTypes = {
    'CARD': "card",
    'PHONE': "phone",
    'WEAPON': "weapon",
    'FOOD': "food",
    'DRINK': "drink"
};

and on the main inventory the item array's like that

  const [items, setItems] = useState([
    {
      type: "PHONE",
      label: "test",
      itemname: "test",
      pieces: 10,
      itemweight: 0.2
    },
    {
      type: "CARD",
      label: "test5",
      itemname: "test5",
      pieces: 5,
      itemweight: 0.2
    }
  ]);

and the Item Component where i define the Item that is beeing dragged:

const Item = props => {

    const [{ isDragging }, drag] = useDrag({
      item: {
        type: ItemTypes[props.type],
        index: props.index,
        label: props.label,
        itemname: props.name,
        pieces: props.pieces,
        weight: props.itemweight
      },
      collect: (monitor) => ({
        isDragging: !!monitor.isDragging()
      })
    });

so at the end that means i get the error 'Invariant Violation: item type must be defined' when i drop the item on the target container.

2

There are 2 answers

0
mpmeyer On BEST ANSWER

There was a recent change to useDrag, see: https://github.com/react-dnd/react-dnd/releases/tag/v14.0.0

1
GavinBelson On

You would need to move your 'type' key out of the 'item' key because of the DnD v14 API change:

const Item = props => {

    const [{ isDragging }, drag] = useDrag({
      item: {
        index: props.index,
        label: props.label,
        itemname: props.name,
        pieces: props.pieces,
        weight: props.itemweight
      },
      type: ItemTypes[props.type], //MOVE THIS OUTSIDE ITEM OBJECT
      collect: (monitor) => ({
        isDragging: !!monitor.isDragging()
      })
    });

TLDR:

Documentation on this: https://github.com/react-dnd/react-dnd/releases/tag/v14.0.0

This should work on all recent React versions. For reference I used:

"react": "^17.0.2",
"react-dnd": "^15.0.2",
"react-dnd-html5-backend": "^15.0.2",