2

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.

4
  • please provide reproducable example in ts playground Commented Jul 26, 2021 at 7:12
  • I think you need to return data from inside function of memo otherwise it will return type void to details which is item time. Commented Jul 26, 2021 at 7:12
  • @PriyankKachhela: thanks that fixed the issue. also is it okay to put the logic in useMemo to solve page reload issue? thanks Commented Jul 26, 2021 at 7:16
  • @stackuser Yes i think it's fine to use memo. Commented Jul 26, 2021 at 7:19

1 Answer 1

1

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]
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.