Home > Net >  How to fetch api when mounting of React.js
How to fetch api when mounting of React.js

Time:06-19

I am trying to display Nfts on my page but it gives and error like Uncaught TypeError: Cannot read properties of undefined (reading 'map'). So my nfts variable is an array but still mapping is not possible. Here is my component:

import React, { useState, useEffect } from "react";
import { Container, Row, Col } from 'react-bootstrap';
import axios from 'axios';
import { Link } from "react-router-dom";

const Nfts = ({ walletAddress }) => {
    const sender = "abc";
    const apikey = "def";
    const [nfts, setNfts] = useState();
    const getNftData = () => {
        axios.get(``)
            .then(output => {
                setNfts(output.data.result)
        })
    }
    useEffect(() => {
        getNftData();
    }, []);
    return (
        <section className="my-nfts">
            <Container>
                <Row>
                    {nfts == '' ?
                        <><div className='mynft-title'>My NFTs</div>
                            <div className="empty-nft">There is no NFT to display</div></> : (
                            <>
                                {nfts.map((nft, index) => {
                                    if (nft.from == sender && nft.to == walletAddress) {
                                        <Col xs={12} md={12} lg={4}>
                                            <div key={index}>{nft}</div>
                                        </Col>

                                    }
                                })}
                            </>
                        )}
                </Row>
            </Container>
        </section>
    );
}

export default Nfts;

So I beleive it doesnt render at the first time when page is loaded. But i might be wrong. What do you think I am making wrong? Thanks..

CodePudding user response:

Just give the nfts State an empty array as initial value For example

const [nfts, setNfts] = useState([]);

or

In the HTML use a conditional statement to not use map method if the nfts still undefined For example

nfts && nfts.map(() => { ... } )

Also, I noticed that the API URL is empty. ( I'm not sure if you mean that because you don't want to show the API URL in the question or you missing that ).

CodePudding user response:

I'm suggest much cleaner syntax for you

nfts?.map((item) => { ...item } )

  • Related