3

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?

1 Answer 1

6

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;

Observations

Maybe you have a typo?

You are destructing buyerName but rendering BuyerName (with capital B).

Sign up to request clarification or add additional context in comments.

2 Comments

But if order is null, accessing buyerName will throw an error.
@johnnash I added order || {}, now your destructing will work fine. I also added offerDuration = '' so it won't be undefined when you use it in useTimer, but you can change it to what you need. I only added empty string because I don't know what is used in useTimer.

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.