Millenial2020
Millenial2020

Reputation: 2913

React How to create a custom Hook

I want to return data from a custom hook.

import { Spinner } from "../../../shared/feedback/Spinner/Spinner";
import { trpc } from "../../../utils/trpc";

export const useCreateActivity = () => {
  // this returns a campaign array
  const { data: campaigns } = trpc.campaign.getCampaigns.useQuery();

  if (!campaigns) {
    return <Spinner />;
  }

  return {
    campaigns,
  };
};


Here I'm calling this hook

  const { campaigns } = useCreateActivity();

  const onSubmit = (data: Campaign) => {
    console.log(campaigns);
  };

  console.log("campaigns", campaigns);

But as you can see I'm getting this error. enter image description here

I don't understand what's going on. It seems pretty simple.

Upvotes: 0

Views: 223

Answers (1)

MauricioRobayo
MauricioRobayo

Reputation: 2356

the hook can return an Element or campaigns:

if (!campaigns) {
  return <Spinner />;
}

return {
  campaigns,
};

So, when you destructure campaingns, the returned value of the hook could be the <Spinner /> element or the campaigns. Typescript does not know which it is, and since the <Spinner /> has no campaigns property you get the error.

You could return just the campaigns from you hook:

export const useCreateActivity = () => {
  const {data} = trpc.campaign.getCampaigns.useQuery();
  return data;
};

And in your component do the conditional logic, something along this lines (untested, very rough code):

  const data = useCreateActivity();

  const onSubmit = () => {
    if (!data) return;
    
    // here you know you will have the campaigns
    const { campaigns } = data
    console.log(campaigns);
  };


  // ...

  if (!data) {
    return <Spinner />;
  }

Upvotes: 2

Related Questions