[SOLVED] Async API Call & Return to Object Giving: Undefined or JSON Error

Hey All!

Iā€™m coding a return in Next React for the API and I am running into an issue with an Async JSON Call. I either am getting Undefined or am getting the output of the API call in console but I can print out the value. Has anyone come across this before? Thanks!

Below is my code, I tried to clean it up the best I could:

mport Moralis from "moralis";
import { useMoralis } from "react-moralis";

//import { GetVars, GetNFT } from "./GetNFTs.js";
import React,{  Component  } from 'react';

const options = { 
    chain: 'matic', 
    address: '0x687d2220075b787fbce0ae2813f9030d3a7e3f08',
    token_address: '0xcdFea41c4A8e70Fb4838426069483dC50cbf5041'
  }

class GetNFT {
  async FetchNFT(){
    return await ({
        data: await Moralis.Web3API.account.getNFTsForContract(options)
    })
  }
}
export class Founder extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        error: null,
        isLoaded: false,
        data: {}
      };
    }

   async componentDidMount() {
    const polygonNFTz = new GetNFT;
    polygonNFTz.FetchNFT()
    const data = polygonNFTz.FetchNFT()
        fetch(data)
        //const res = JSON.stringify(data)
        //.then(res => JSON.parse(res))
        .then(res => res.json())
        //.then((response) => response.json())
        .then(
          (result) => {
            this.setState({
              isLoaded: true,
              data: result
            });
          },
          // error handler
          (error) => {
            this.setState({
              isLoaded: true,
              error
            });
          }
        )
    }
    
  
    render() {
    
      const { error, isLoaded, data } = this.state;

      if (error) {
        return (
          <div className="col">
            Error: {error.message}
          </div>
        );
      } else if (!isLoaded) {
        return (
          <div className="col">
            Loading...
          </div>
        );
      } else {
        
        return (
            <div className="col">
            {data.map(data => <div>{data.total}</div>)}
            </div>
          );
        }
    }
}

Screen Shot 2022-02-23 at 7.28.23 AM

I was able to resolve the the issue with the following code. I just wanted to update this in case it helps someone out.

import {  useMoralis } from "react-moralis";
import ReactDOM from 'react-dom';
import React,{  Component, useState, useEffect  } from 'react';





class GetNFT {
  async FetchNFT(){
    const Moralis = require('moralis');//00017
    const appId = process.env.NEXT_PUBLIC_REACT_APP_MORALIS_APP_ID;
    const serverUrl = process.env.NEXT_PUBLIC_REACT_APP_MORALIS_SERVER_ID;
    Moralis.initialize(appId);
    Moralis.serverURL = serverUrl;
    Moralis.start({appId, serverUrl});
    const options = { 
  
      chain: 'matic', 
      address: useMoralis.user,//user,
      token_address: '0xcdFea41c4A8e70Fb4838426069483dC50cbf5041'
    }

    return await ({
        data: await Moralis.Web3API.account.getNFTsForContract(options)
    })
  }
}
export const Parent = () => {
   // const [mounted, setMounted] = useState(true);
    return (
      <div>
        { <Child />}
      </div>
    );
  };

const Child = () => {
  const Moralis = require('moralis');//00017

    const [state, setState] = useState("loading (4 sec)...");
    const [data, setData] = useState();
    useEffect(async () => {
        const polygonNFTz = new GetNFT();
        const a = await polygonNFTz.FetchNFT();
        console.log(a);
        const data = await a.data.total;
        setData(data);
      fetchData();
      /*let isMounted = true;
      return () => {
        isMounted = false;
      };*/
      // simulate some Web API fetching
        function fetchData() {
        setTimeout(() => {
          // drop "if (isMounted)" to trigger error again 
          // (take IDE, doesn't work with stack snippet)
          setState(data)//if (isMounted) 
          //else console.log("aborted setState on unmounted component")
        }, 4000);
      }
    }, []);
  
    return <div>{data}</div>;
  };
2 Likes