Reputation: 424
I have a functional react component which uses custom hook useTimer.This component receives data from API(via redux store).
function RenderRespond(order) {
if(order === null) return;
const {
buyerName,
offerDuration,
} = order;
const {
seconds,
minutes,
} = useTimer(offerDuration);
return(
<div>
{BuyerName}
{minutes}:{seconds}
</div>
);
}
I only want to render this component when order is not null.The code throws the error that hooks cannot be conditionally rendered.How can I achieve this?
Upvotes: 3
Views: 10408
Reputation: 31565
You should call useTimer
before the if statement.
Like so:
function RenderRespond(order) {
const {
buyerName,
offerDuration = '', // not sure what the default value will be, but you can change it for your needs
} = order || {};
const {
seconds,
minutes,
} = useTimer(offerDuration);
if(order === null) return null;
return(
<div>
{BuyerName}
{minutes}:{seconds}
</div>
);
}
If you look at the docs the reason why this happens is because if(order === null) return
will prevent the hook to be called, but it will be expecting it to be called;
Maybe you have a typo?
You are destructing buyerName
but rendering BuyerName
(with capital B).
Upvotes: 6