Daniels0n
Daniels0n

Reputation: 93

React typescript passing function as prop and calling from child component

I'm passing in a function to a child component, that manages my state in the parent component. It takes an object, that is declared in FriendListItem and sets it to the array as a new object. I have been researching but can not figure it out.

interface FriendListItem {
  id: number;
  name: string;
  address: string;
}

the function

 const [friendList, setFriendList] = useState<FriendListItem[]>([]);

  const addToFriendList = (friend: FriendListItem): void => {
    setFriendList((prevstate) => [...prevstate, friend]);
  };

I'm passing it to the child component

<UserDetail addFriend={addToFriendList} />

and this is my child component code, I'm telling (or trying to) the component, the function will take friend arg and return void. But when I pass that in I get an error

This expression is not callable.
  Type 'FuncProps' has no call signatures.ts(2349)

Code:

interface FriendListItem {
  id: number;
  name: string;
  address: string;
}

interface FuncProps {
  addFriend: (friend: FriendListItem) => void;
}

const UserDetail = (addFriend: FuncProps) => {
  const { userId } = useParams<UserIdParams>();
  const { data, done } = useFetchOne(
    `https://jsonplaceholder.typicode.com/users/${userId}`
  );

  const handleClick = () => {
    const friend: FriendListItem = {
      id: data!.id,
      name: data!.name,
      address: data!.address.street,
    };
    addFriend(friend);
  };

Upvotes: 0

Views: 2555

Answers (2)

P4R3A
P4R3A

Reputation: 1099

the first argument of your component is an object, which contains passed props, you have to get it from props object, e.g:

interface UserDetailProps {
   addFriend: FuncProps
}

connst UserDetail: FC<UserDetailProps> = ({addFriend}) => {...}

Upvotes: 1

Shyam
Shyam

Reputation: 5497

you need to change it as

const UserDetail = ({addFriend}: FuncProps) => { ... } 

or

const UserDetail: React.FC<FuncProps> = ({addFriend}) => { .... } 

Upvotes: 2

Related Questions