Search code examples
reactjsarraysdropdownhtml-select

Trying to fetch <select> from array in React


I am trying to fetch a dropdown select list from an array:

Select user ids from a smart contract:

const [ownerIds, setOwnerIds] = useState(null);
useEffect(() => {
  const checkOwners = async () => {
    if (ethereum) {
      //MetaMask injects a Web3 Provider as "web3.currentProvider", exposes the ethers.js Provider API.
      const provider = new ethers.providers.Web3Provider(ethereum);
      //There is only ever up to one account in MetaMask exposed
      const signer = provider.getSigner();
      const nftContract = new ethers.Contract(contractAddress, abi, signer);      
        if (currentAccount !== null && nftContract !== null) {
          let ownerTokenId = await nftContract.tokensOfOwner(currentAccount);
            if(ownerTokenId.length > 0) {
              setTokenId(true);              
              setOwnerIds(ownerTokenId.toString().split(','));              
            } else {
                setTokenId(false);              
              }           
        }
    }
  };
  checkOwners()
},[currentAccount,ethereum]);

Here is the function I did trying to map the ids.

        <select>
          {ownerIds.map((id) => {return<option>{id.ownerIds}</option>})}
          {console.log(ownerIds)}
        </select>

This is the console.log result:

(3) ['70', '71', '73']
0: "70"
1: "71"
2: "73"
length: 3
[[Prototype]]: Array(0)

My dropdown list is showing 3 blank options, and if I just print ownerIds it returns 707173.


Solution

  • You should show the id directly since ownerIds is an array of strings:

    <select>
      {ownerIds.map((id) => {
        return <option key={id}>{id}</option>;
      })}
    </select>;