3

I'm struggling on using a hook on each item on an array within my React Typescript project.

Without considering the limitations on using hooks, the code would be the following:

const forwardContractArray = useGetForwardArray()

interface ForwardResult {
        token: string;
        amount: number;
        expiryTime: number;
    }

const forwardResultArray: Array<ForwardResult> = []

for (let forwardAddress of forwardContractArray) {
  const { token, amount, expiryTime} = useForwardInfo(forwardAddress)
  forwardResultArray.push({token, amount, expiryTime})
}

Because of the limitations on running hooks in a for loop this is not possible to use a for loop for this.

Please could someone direct me on how to implement such a function within the scopes of React?

Thanks in advance.

2
  • 1
    provide please a minimal verifiable example stackoverflow.com/help/minimal-reproducible-example or codesandbox link or repo link so we can help knowing what are you exactly trying to achieve. Thank you Commented Dec 7, 2021 at 19:24
  • Either your useForwardInfo should be returning an array, or you should be rendering a unique component for each usage of useForwardInfo. Commented Dec 7, 2021 at 22:25

1 Answer 1

2

React is first and foremost a UI library - so, if you want to show something for each element of an array, then you can have a component per item and inside the component you can use a single hook

return (
  <>
    { forwardContractArray
        .map(item => <ItemDisplay key={item.token} item={item} />) }
  </>
)

and then e.g.

function ItemDisplay({ item } : { item: ForwardResult }) {
  const { token, amount, expiryTime} = useForwardInfo(item);
  return (
    <p>Whatever you want to show for this item</p>
  )
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks this works! For my useGetForwardArray() hook how do I stop this rendering every second? Preferably would only like this to render when the forward array is updated!
From your code it can't be seen why it should render every second - react learns about changes through e.g. useState hook or similar - check where and how you use it.

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.