Home > Back-end >  React - How to use hook useState props to create a map function
React - How to use hook useState props to create a map function

Time:02-18

I am trying to use props to create a map, but it shows this error:

TypeError: data.map is not a function

Here is the code of the main page:

const Portfolio = () => {
  
  const [portfolio_assets, setPortfolioAssets] = useState([]);
  const auth = useContext(AuthContext);
  const onFetchPortfolioAssets = useCallback(async () => {
      const json = await fetchPortfolioAssets(auth.token);
      if (json) {
          setPortfolioAssets(json);
      }
      }, [auth.token]);
      useEffect(() => {
      onFetchPortfolioAssets();
      }, [onFetchPortfolioAssets]);

  return (
    <MainLayout>
       <Dashboard data={portfolio_assets} />
    </MainLayout>
  )
};

export default Portfolio;

this is the page with Dashboard:

const Dashboard = (data=[]) => {
    console.log(data)
    
    return (
        <Row>
            <table className='table table-striped'>
                <tr>
                    <th>Category</th>
                </tr>
                {data.map((portfolio_asset) => (
                <tr key={portfolio_asset.id} lg={12}>
                    <td>{portfolio_asset.category}</td>                    
                </tr>
                ))}
            </table>
        </Row>
  )
};

export default Dashboard;

Here is the console.log, so the object is there, but i didn`t understand how to use .map

{data: Array(0)}data: [][[Prototype]]: Object

{
    "data": [
        {
            "id": 1,
            "category": "Category 1",
        },
        {
            "id": 2,
            "category": "Category 2",
        },
        {
            "id": 3,
            "category": "Category 2",
        },
    ]
}

CodePudding user response:

You made a mistake by getting data object in Dashboard. The parameter you get contains all the props, not only data, so you have to replace it by :

const Dashboard = ({data=[]}) => {

with {} around data to get data from the props object

  • Related