setState in parent component using parameter in child

Viewed 51

I'm trying to call setList (set of useState hook) from child component but react retrieve the error: TypeError setList is not a function

here the parent component. I pass the handleDrop to the Box component:

import React, { memo, useState } from "react";
import { Dustbin } from "./Dustbin";
import { Box } from "./Box";
export const Container = memo(function Container() {
    const { list, setList } = useState();
    
    const handleDrop= (item)=>{
        console.log("dopped", item);
        setList(item);
    }

  return (
    <div>
      <div style={{ overflow: "hidden", clear: "both" }}>
        <Dustbin list={list} />
      </div>
      <div style={{ overflow: "hidden", clear: "both" }}>
        <Box name="Glass" handleDrop={handleDrop} />
        <Box name="Banana" handleDrop={handleDrop} />
        <Box name="Paper" handleDrop={handleDrop} />
      </div>
    </div>
  );
});

here the Box component:

import React from "react";
import { useDrag } from "react-dnd";
import { ItemTypes } from "./ItemTypes";
const style = {
  border: "1px dashed gray",
  backgroundColor: "white",
  padding: "0.5rem 1rem",
  marginRight: "1.5rem",
  marginBottom: "1.5rem",
  cursor: "move",
  float: "left"
};
export const Box = ({ name, handleDrop }) => {
  const [{ isDragging }, drag] = useDrag({
    item: { name, type: ItemTypes.BOX },
    end: (item, monitor) => {
      const dropResult = monitor.getDropResult();
      if (item && dropResult) {
        handleDrop({pippo: item.name}); //here the call
        console.log(item);
      }
    },
    collect: (monitor) => ({
      isDragging: monitor.isDragging()
    })
  });
  const opacity = isDragging ? 0.4 : 1;
  return (
    <div ref={drag} style={{ ...style, opacity }}>
      {name}
    </div>
  );
};

what am i missing here?

1 Answers

useState returns an Array not object,

instead of

const { list, setList } = useState();

do

const [list, setList ] = useState();
Related