Hello, I have a request question

hello I have 2 problems and I can’t see them, my problem is:

I have a function that the user asks me for comparing the owner address with the user address. The error is that when it asks for the data in the cloud, if I don’t put the try catch, it gives me an error: Cannot read properties of undefined (reading ‘attributes’) , but if I put the try catch , the error is: that the request is pending and in no way have I been able to extract the data that the request returns to me, it is a basic request, if I am wrong in something, please could you help me and explain what I do bad, thanks.

cloud function :

Moralis.Cloud.define('getUserByCollection', async function(request){

  try{

  const { ownerAddress }  = request.params

  const query = new Parse.Query('_User')

  query.equalTo('ethAddress', ownerAddress);

  const results = await query.first({ useMasterKey: true });   //.find();

 

  const userAvatar = (results.attributes.userAvatar != null || undefined) ? results.attributes.userAvatar : ''

  const userBanner = (results.attributes.userBanner != null || undefined) ? results.attributes.userBanner : ''

  const username = (results.attributes.username != null || undefined) ? results.attributes.username : '';

  const ethAddress = (results.attributes.ethAddress != null || undefined) ? results.attributes.ethAddress : ''

    const user = {

      "info": 'entro en getUserByCollection',

      "userAvatar": userAvatar,

      "userBanner": userBanner,

      "username": username,

      "ethAddress": ethAddress,

    };

   

  return user

     

  }catch(e){

    return e

  }

});

request function:

const getUserByCollecFunc = async ( ownerAddress: string) => {

        let results = await Moralis.Cloud.run('getUserByCollection', {ownerAddress})

        console.log( results )

        console.log(ownerAddress)

        return results

        // dispatch({

        // type: 'SET_RENDER_USER_BY_COLLECTION',

        // payload: user

        // })

       

    }

render data front :

import CardCollections from '@components/cards/card-collections';

import ArrowBackOutlinedIcon from '@mui/icons-material/ArrowBackOutlined';

import ArrowForwardOutlinedIcon from '@mui/icons-material/ArrowForwardOutlined';

import Box from '@mui/material/Box';

import Stack from '@mui/material/Stack';

import Typography from '@mui/material/Typography';

import React, { useContext, useEffect } from "react";

import Carousel from "react-multi-carousel";

import CollectionState from "@context/renderCollection-context/CollectionContext";

const TitleAndController = () => {

  return (

    <Stack

      direction='row'

      sx={{

        alignItems: 'center',

        justifyContent: 'space-between',

        mb: { xs: 2, sm: 3, md: 3, lg: 3 }

      }}

    >

      <Typography

        sx={{

          fontFamily: "Poppins_400Regular",

          color: "#FFFFFF",

          alignSelf: 'center',

          fontSize: { xs: 22, sm: 26, md: 32, lg: 38, xl: 44 }

        }}

      >

        Hot Collections

      </Typography>

      <Stack

        direction='row'

        alignItems='center'

        spacing={{ xs: 1.5, sm: 2, md: 3, xl: 4 }}

      >

        <ArrowBackOutlinedIcon

          sx={{

            color: '#fff',

            fontSize: { xs: 25, sm: 26, md: 28, lg: 28, xl: 28 }

          }}

          onClick={() => this.r.current?.next()}

          style={{ cursor: 'pointer' }}

        />

        <ArrowForwardOutlinedIcon

          sx={{

            color: '#fff',

            fontSize: { xs: 25, sm: 26, md: 28, lg: 28, xl: 28 }

          }}

          onClick={() => this.r.current?.prev()}

          style={{ cursor: 'pointer' }}

        />

      </Stack>

    </Stack>

  )

}

const responsive = {

  superLargeDesktop: {

    // the naming can be any, depends on you.

    breakpoint: { max: 4000, min: 1250 },

    items: 5

  },

  desktop: {

    breakpoint: { max: 1249, min: 1100 },

    items: 4

  },

  laptop: {

    breakpoint: { max: 1099, min: 750 },

    items: 3

  },

  tablet: {

    breakpoint: { max: 749, min: 650 },

    items: 2

  },

  mobile: {

    breakpoint: { max: 649, min: 0 },

    items: 1

  }

};

export default function CarouselCollection() {

  const {

    userByCollectionRender,

    collectionRender,

    userRenderFunc,

    getCollectionFunc,

    getUserByCollecFunc,

  } = useContext(CollectionState);

  const [ collectionStateRender, setCollectionStateRender] = React.useState([])

 

  let collectionRenderSlice = collectionStateRender

  .slice(0, 30)

 

  useEffect( () => {

    async function fetchData() {

     

     await getCollectionFunc()

    }

   

  fetchData()

  }, []);

  useEffect(() => {

    setCollectionStateRender(collectionRender);

  }, [getCollectionFunc]);

  console.log(collectionRender)

//ethAddress

  return (


    <Stack

      spacing={{ xs: 2, sm: 4, md: 4, lg: 4 }}

      sx={{

        backgroundColor: '#16151A',

        justifyContent: 'center',

      }}

    >

      <Stack

        my={{ xs: 2, sm: 3, md: 3, lg: 5 }}

        mx='auto'

        sx={{ maxWidth: '90%' }}

      >

        <TitleAndController />

        <Carousel

          responsive={responsive}

          removeArrowOnDeviceType={[ "mobile", "tablet", "laptop", "desktop", "superLargeDesktop"]}

        >

          {collectionRenderSlice.map(( collection ) => {

            let name = collection.attributes.name

            let owner = collection.attributes.owner

            let filePath = collection.attributes.filePath

            const userRend = userRenderFunc(owner)

            console.log(userRenderFunc)

           

            return (

              <Box key={collection.id}>

                <CardCollections

                  name={name}

                  filePath={filePath}

                  owner={owner}

                  ownerAvatar={userRend}

                />

              </Box>

            );

          })}

        </Carousel>

      </Stack>

    </Stack>

  )

}

The error is that when it asks for the data in the cloud, if I don’t put the try catch, it gives me an error: Cannot read properties of undefined (reading ‘attributes’)

This will happen if there’s no results found with your query i.e. if you try to use attributes on nothing. You could just add a statement checking if results has some value or not:

if (results) {
 const userAvatar..

  ..

  return user;
}

But otherwise you can use try catch like you’re doing now.

but if I put the try catch , the error is: that the request is pending

What is the exact error?

the error comes from the cloud of .attributes and if I understand that it is because it does not exist, it would be rather to validate the cloud and the incoming values, the problem really is that when the cloud responds it remains:

2022-09-30_21h52_25

In the previous code there is the query to the table, I cannot make it change the promise of the pending state and I cannot access its values or that the function returns the values. because it is always pending. I apply a JSON.parse or a result.json() and nothing works for me to extract the data and inside it if it contains the results

You have to wait for that promise to resolve e.g. with await. So check your usage of userRenderFunc - I think that’s where it’s coming from.

It doesn’t have it because I was testing it, I put await on it and it doesn’t resolve it either

const userRenderFunc = async ( ownerAddress: string) => {

       const result = await getUserByCollecFunc(ownerAddress)

        return result

    }

Find out where that promise pending is coming from exactly (remove parts of your code until you find it).

If it’s this: const userRend = userRenderFunc(owner), you would need await here as well but you will need to handle it differently since you’re trying to render directly - you could use a separate async function or useEffect that you use that map with which updates a state (useState) and then you use that state to render (map) with instead.

You need to think of any use of data that you’re fetching (promises).

May be easier if you share a repo.