Moralis Query and useState()

Hi guys, I’m trying to fetch data from my db with moralis and set the response to what I get.

const { isInitialized, Moralis } = useMoralis();
  const [isLoading, setIsLoading] = useState(false);
  let [eventInfo, setEventInfo] = useState(null);
  let [error, setError] = useState(null);
  const params = useParams();

  useEffect(() => {
    const fetchData = async () => {
      try {
        const query = new Moralis.Query('ContractCreated');
        query.equalTo('contractAddress', params.contractId);
        await query.find()
        .then(response => {
      catch (error) {
  }, [isInitialized]);

the response[0].attributes is what I need to set eventInfo to.

However when I do setEventInfo(response[0].attributes) and that later on I render this I get an error because it says eventInfo is undefined.

return (
      <div style={{ paddingTop: '50vh' }}>
        <h1 style={{ color: 'black' }}>Event {params.contractId}</h1>
        <div style={{color:'black'}}>

TypeError: Cannot read properties of null (reading ‘eventName’)

try only {eventInfo} instead of {eventInfo.eventName}

or check if is undefined before trying to access .eventName as it may be undefined initially before it is set

I can’t use {eventInfo} because react cannot render object.
and I check that it’s not undefined and it’s not thats what I don’t understand
I also want to add that in my useEffect if I console log eventInfo.EventName I get the correct thing

try {JSON.stringify(eventInfo)}

EDIT: after setting data in the useEffect
I just do a

{data && 
              <h2 style={{color:'black'}}>Event name: {data.eventName}</h2>

so it will only render if data is not undefined which seems to work fine after refreshing the page manually as well.

Yes you always need to do something like this if you are rendering data that doesn’t exist yet, unless the initial state is valid e.g. useState([]) and map. Otherwise you will get errors as you’ve found.

You can try it this way

You can make this setEventInfo(response[0])

And make this <p>{eventInfo.get("eventName")}</p>

Hi replacing




does not work.
get is not a function.

You can try fix it with this <p>{eventInfo?.get("eventName")}</p>

This is will a case if your queried object isn’t updated yet