简体   繁体   中英

How to fix error type void is not assignable to type using react and typescript?

i have the code like below which works.

const { loading, data, error, refetch } = useItemDetailsQuery({
    variables,
    notifyOnNetworkStatusChange: true,
    fetchPolicy: 'network-only',
});

const details: Partial<Item> = data?.itemDetails
    ? data.itemDetails
    : {};

type Item = ItemDetailsQuery['itemDetails'];

type itemDetailsQuery = {
    itemDetails: Pick<
        Types.ItemDetails,
        | 'created'
        | 'description'
        | 'name'
    >
 };

Now with above code, the data in details doesnt get updated page refresh. so i am thinking to put the calculation logic of details in useMemo such that it calculates this logic when data changes and hence there would be no need to reload the page to view new data.

so i tried putting the logic in useMemo like so

const details: Partial<Item> = React.useMemo(
    () => { data?.itemDetails
        ? data.itemDetails
        : {}
    }, [data]
);

but this gives me error "Type 'void' is not assignable to type 'Partial<Pick<ItemDetails, "created", "description", "name"}>"

I am not sure how to fix this problem. could someone help me with this. thanks.

I am new to using react and typescript. In the process of learning.

you forgot the return in useMemo. Without return in the curry function, the value of details will be undefined type as void.

const details: Partial<Item> = React.useMemo(
    () => { 
        return data?.itemDetails
        ? data.itemDetails
        : {}
    }, [data]
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM