0

Hello Everyone Here is my next js code actually I try to fetch the event data from smart contract but when I mapping the data this error is occur TypeError: Cannot read properties of undefined (reading 'map')Can anyone help me to fix this error.

'use client'
import React, { useEffect, useState } from 'react'
import campaignFactory from '../../artifacts/contracts/campaign.sol/campaignFactory.json';
import { ethers } from 'ethers';
const Home = ({AllData}) => {
  const [filter,setFilter]=useState(AllData);
  useEffect(()=>{
    filter.map((e)=>{

      console.log(e.title);
    })
  },[]);
  return (
    <div>
      <button onClick={()=>setFilter(AllData)}></button>
      </div>
  )
}


export async function getStaticProps() {
  const provider = new ethers.providers.JsonRpcProvider(
    process.env.NEXT_PUBLIC_RPC_URL
  );

  const contract = new ethers.Contract(
    process.env.NEXT_PUBLIC_ADDRESS,
    campaignFactory.abi,
    provider
  );

  const getAllCampaigns = contract.filters.campaignCreated();
  const AllCampaigns = await contract.queryFilter(getAllCampaigns);
  const AllData = AllCampaigns.map((e) => {
    return {
      title: e.args.title,
      image: e.args.imgUrl,
    }
  });
  return {
    props: {
      AllData,
    },
    revalidate: 10
  }

}
export default Home
3
  • Hey can you give me more information, which part is not working? Jun 14, 2023 at 7:03
  • filter.map((e)=>{ console.log(e.title); TypeError: Cannot read properties of undefined (reading 'map') Jun 14, 2023 at 8:51
  • map will work only on arrays, check whether filter is any array. Jun 15, 2023 at 5:58

2 Answers 2

1

You are setting your state with setFilter at the press of the button "onClick()" but you are mapping the state as soon as the components are rendered with useEffect. See useEffect documentation for more information.

You can try to create a new function that sets your state and then maps it, and call that in the onClick().

0
'use client'
import React, { useEffect, useState } from 'react'
import campaignFactory from '../../artifacts/contracts/campaign.sol/campaignFactory.json';
import { ethers } from 'ethers';
const Home = ({AllData}) => {
  const [filter,setFilter]=useState([]);

const getAllData = () => {
  setFilter(AllData);
}

const showAllCampaigns = () => (
  filter.map((item)=>console.log(item))
)

  return (
    <div>
      <button onClick={()=>setFilter(AllData)}></button>
      {filter.length > 0 ? showAllCampaigns: null}
      </div>
  )
}
2
  • thanks for your cooperation I also did the same but its also not working Jun 13, 2023 at 6:26
  • Check whether filter is any array, map will work only for arrays. Jun 15, 2023 at 5:59

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.