Challenges with managing state in React and NextJS

I'm currently facing a challenge with my script in NextJS/React where I am finding it difficult to save state and reuse data in a variable.

import React from 'react';
import Head from 'next/head'
import Image from 'next/image'
import axios from 'axios';
import styles from '../styles/Home.module.css'

export default function Home() {

const [ETHdata, setETHData] = React.useState({ });

const [CryptoDATA, setCryptoDATA] = React.useState({ });

Everything seems to be running smoothly at this point :)

However, the issue arises when I try to fetch data from an API:

  const fetchETH = async () => {
    const res = await axios.get('https://api.coingecko.com/api/v3/simple/price?ids=Ethereum&vs_currencies=CHF&include_24hr_change=true'); 
    
    if (res.data && res.data.ethereum) {
      setETHData(res.data.ethereum);
    }
}

Instead of rewriting the same code for multiple cryptocurrencies, I decided to fetch them all at once here:

const fetchCryptoDATA = async () => {
  const res = await axios.get('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin%2Cethereum%2Ccrypto-com-chain%2Csolana%2Cavalanche-2%2Cblockstack%2Cflow%2Clitecoin%2Calgorand%2Ccardano&vs_currencies=CHF&include_24hr_change=true'); 

if (res.data ) {
    setCryptoDATA(res.data);
}
console.log(CryptoDATA)
}

When displaying the fetched data:

 React.useEffect(() => {
    fetchETH();
    fetchCryptoDATA();
  }, []);
  return (
...

everything works as expected

<p>Ethereum {ETHdata['chf']}   {parseFloat(ETHdata['chf_24h_change']).toFixed(2)}</p>

But

<p>ETHEREUM {CryptoDATA['ethereum']['chf']}   {parseFloat(CryptoDATA['ethereum']['chf_24h_change']).toFixed(2)}</p>

initially displays correctly, but on subsequent loads, it returns

"Cannot read property 'chf' of undefined"

I believe it's a small issue that I may have overlooked and would appreciate any assistance you can provide!

Answer №1

If CryptoDATA['ethereum'] is potentially undefined, it could be due to the initial state of CryptoDATA being an empty object:

const [CryptoDATA, setCryptoDATA] = React.useState({ });

To address this issue, one solution is to set the initial state with the expected structure:

const [CryptoDATA, setCryptoDATA] = React.useState({ ethereum: { } });

An alternative approach is to use optional chaining when accessing properties of objects that may be undefined:

CryptoDATA.ethereum?.chf

Alternatively, you can check if the property exists before accessing it:

CryptoDATA['ethereum'] ? CryptoDATA['ethereum']['chf'] : null

Another way to handle this situation is by tracking a loading state during AJAX operations and not rendering this section until the data is available, using a spinner or loading indicator instead.

Regardless of the method chosen, the main point remains the same - avoid referencing properties on undefined objects. Since the AJAX operation completes after the initial render, the object being accessed is initially undefined.

Answer №2

Insert the following line into your script.

ETHEREUM {CryptoDATA['ethereum']?.['chf']} {parseFloat(CryptoDATA['ethereum']?.['chf_24h_change'])?.toFixed(2)}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Next Auth custom redirecting to a subdomain

Encountering a problem with NextAuth when trying to redirect back to a subdomain post successful login. I have configured a custom OAuthProvider as per the instructions provided here. My application is operating across multiple subdomains, each using a dif ...

The TextField component in Material UI keeps its value visible even when typing in the field, unlike other components where the value is hidden

Since diving into Material UI, I've encountered an odd issue with the hintText in a TextField Component from Material UI. Below is my code snippet: /* in my component ... */ /* ... */ render() { const actions = [ <FlatButton ...

I encountered a TypeScript error in React Native when attempting to use "className" with TypeScript

Although I've been using React for a while, React Native is new to me. I recently started using tailwind with import { View, Text } from "react-native"; import React from "react"; export default function Navigation() { return ...

Ways to dynamically include onClick on a div in a react component based on certain conditions

Is it possible to conditionally set the onClick event on a div element in React based on the value of a property called canClick? Instead of directly checking this.state in the event handler, I am hoping to find a way to implement this logic within the re ...

A beginner's guide to implementing syntax code highlighting with next-mdx-remote

My goal is to showcase my code syntax utilizing next-mdx-remote on my Nextjs website. I'm fetching my markdown content from graphcms and displaying it in the following way: import { serialize } from "next-mdx-remote/serialize" import { MDXRemote } fr ...

Issue encountered when trying to utilize Firestore in a React component: TypeError occurs as db.collection is not recognized as a

I am facing an issue while attempting to utilize Firestore within my React component. The specific error message reads "Unhandled Runtime Error: TypeError: firebase_firebaseConfig__WEBPACK_IMPORTED_MODULE_4_.db.collection is not a function." I am utilizing ...

Having issues with Tailwind classes not being applied properly on dynamically generated pages in Gatsby-node

Currently, I am working on building dynamic pages using gatsby-node. The templates for these pages are stored in the templates/ directory. However, I have run into an issue where I cannot utilize tailwind classes within these templates unless they are al ...

Steps for aligning a grid column to the same height as the element above it and moving it to the left side

I have a setup using material UI where I have a grid positioned on top of a Paper element. Within the grid, there is a text input field in the first column that I want to match the height of the paper element and be aligned with its left border. I have tri ...

There is an issue with types in React when using TypeScript: The type '(user: User) => Element' cannot be assigned to the type '((props: User) => any) & ReactNode'

I'm encountering an error in the terminal and need some assistance. I am not well-versed in TypeScript, so any guidance to resolve this issue would be highly appreciated. https://i.stack.imgur.com/PWATV.png The Loadable component code: import { Circ ...

Encountering an unexpected error: receiving a void element tag as input in React

Any ideas on how to resolve the following error message: input is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML` Check out my code snippet below: import "./styles.css"; export default function App() { re ...

Creating various containers in React JS for different components

I am faced with the task of rendering multiple DOM elements from my JavaScript code. Imagine I have div elements like this: <div id="div1"><div> //Some Html tags <div id="div2"><div> //Some Html tags <div id="div3" ...

It appears that React Query is not retaining cached data

After watching a tutorial on YouTube about utilizing React Query, I attempted to implement caching in my project. However, the data is fetched every time instead of being retrieved from the cache. I've reviewed my code and can't pinpoint what I&a ...

When you use the useState object in NextJS, the context object may appear to be empty

I've encountered an issue while trying to pass a context object in NextJS that uses data from a useState hook. Strangely, the state variable and setState functions are undefined when consumed. It's puzzling because substituting a simple variable ...

What is the best way to send a POST request using axios with both body and form data included at the

Is there a way to successfully send a post request using Axios that includes both body data and form data? I am having trouble getting the data to reach my route handler: axios({ method: 'POST', url: `${keys.SERVER_URL}/post/new-post/${i ...

What is the process for logging out when a different user signs in using Firebase authentication in a React Native application?

I am new to React Native and facing challenges with managing authentication state in my application. Currently, I am using Redux but have not yet implemented persistence for user login. I have incorporated Firebase authentication. Essentially, I would li ...

Warning in Jest: "Unable to assign refs to function components" when using TypeScript with functional components setup

Currently, the setup involves React 18 along with up-to-date versions of webpack, babel, typescript, jest, and the MaterialUI component library. The application can be run/built without any errors, but a warning is triggered only during the Jest testing of ...

Issue: The module 'react-dev-utils/getPublicUrlOrPath' cannot be located

I recently deployed my React.js application on Heroku but encountered a message stating: The Browserslist indicates that caniuse-lite is outdated and advises to run the following command: npm update. In response, I executed npm update followed by ...

Having trouble getting react router to function properly with multi-layer routes containing parameters

I have been working on configuring my react-router and so far it has been smooth sailing with simple routes like: /login, /logout, /admin. However, I am now facing an issue with setting up a route like this: /admin/groups/modify/:groupID. While the /admin/ ...

What is the best way to incorporate scratch card animation into a React Native application?

How can I create a scratch card animation using React Native? What strategies should I consider in order to achieve this outcome? While I am aware of existing libraries that may assist with this task, I am particularly interested in exploring different ap ...

Could React Native EXPO-CLI be utilized to enable video calling functionality?

Looking for a way to establish a video call connection between two clients, one using react Js and the other utilizing react native with expo-cli. Unsure if this is achievable under these circumstances. Any examples or alternatives would be greatly appre ...