Unable to show information post retrieval

My current challenge involves fetching data from a REST endpoint using axios, rendering it in my app.js component, and then sharing it with the entire app through the context API:

axios.js

import axios from 'axios';

const instance = axios.create({
    baseURL: 'api_endpoint'
});


export default instance;

app.js

import Context from './context'

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      comp: []
    }
  };
async componentDidMount() {
     await instance.get('')
      .then(res => {
          const data = JSON.stringify(res.data.data)
          this.setState({comp: data});
          console.table('componentDidMount', data); // here I can log the data
      })
      .catch(err => {
        console.log(err)
      });

  }

 render () {
    return (

      <Context.Provider 
        value={{
          comp: this.state.comp
        }}>
      </comp.Provider>

    );
  }
}

export default App;

children.js

import Context from '../../context'

class Children extends Component { 
    render () {
        const { classes } = this.props;
        return (
          <Context.Consumer>
                    {context => (
                  <Paper className={classes.root}>
                    <Table className={classes.table}>
                      <TableHead>
                        <TableRow>
                          <CustomTableCell>comp_id</CustomTableCell>
                          <CustomTableCell align="right">comp_name</CustomTableCell>
                          <CustomTableCell align="right">comp_price</CustomTableCell>
                          <CustomTableCell align="right">comp_log_usd</CustomTableCell>
                        </TableRow>
                      </TableHead>

                      <TableBody>
                        {Object.entries(context.comp).forEach(([key, value]) => (
                          <TableRow className={classes.row} key={value.id}>
                          <CustomTableCell component="th" scope="row">
                            {value.id}
                          </CustomTableCell>
                          <CustomTableCell align="right">{value.name}</CustomTableCell>
                          <CustomTableCell align="right">{value.price}</CustomTableCell>
                          <CustomTableCell align="right">{value.log.usd}</CustomTableCell>
                        </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </Paper>
              )}
            </Context.Consumer>
        );
    }

I have encountered two issues. The first is that despite successfully logging and testing the "log" property, when rendered, an error stating "Cannot read property 'log' of undefined" occurs.

The second issue arises when I remove a CustomTableCell containing this property. It causes my data to load outside the table, displaying the entire array of objects separately.

Any assistance on resolving these challenges would be greatly appreciated.

Answer №1

If you choose to implement async functions, it is advisable to avoid using .then() as it can make tracking difficult. Personally, I find it more manageable to not use async on component did mount. However, here is a suggested alternative approach:

 async componentDidMount() {
  try{
   let response = await instance.get('')
   const data = JSON.stringify(response.data.data)
   this.setState({comp: data});
   console.table('componentDidMount', data); // logging the data
  }
  catch(error){console.log(error);
 }

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

How come my 'Select' components in react are automatically linked together?

I am currently facing an issue with my submission page using materialui. I have designed two 'Select' components on the page, but whenever I choose an option from the second component, it refreshes the option selected in the first component. Whil ...

How to customize the preview grid design in material-ui-dropzone

I am working on a book form page in my React app which includes an option to upload a cover photo. I opted for material-ui-dropzone from https://yuvaleros.github.io/material-ui-dropzone/ and it's working well, but I encountered an issue with the previ ...

Libraries that automatically suggest options for integrating objects described by JSON schema

We are currently developing a platform with an email templating feature. Users can insert objects and variables into their emails using json-schema. Although we are not the first ones to work on this, our research has not turned up many libraries that cou ...

In TypeScript, the 'as const' syntax results in a syntax error due to the missing semicolon

I incorporated the following code into my react project: export const animation = { WAVES: "waves", PULSE: "pulse", } as const; export type Animation = typeof animation[keyof typeof animation]; Upon running the project, I encounte ...

Verify whether the element retains the mouseenter event after a specified delay

I recently implemented some blocks with a mouseenter and mouseleave event. <button onMouseEnter={this.MouseEnter}>hover</button> MouseEnter(e) { setTimeout(() => { // Checking if the mouse is still on this element // Pe ...

Can someone explain the npm install messages from react-compare-app?

Scenario: I recently explored the react-compare-app example from React's examples page and decided to clone the repository. Following the usual procedure, I ran `npm install`. Initially, everything appeared normal as with most installations I have don ...

Trigger a function post-rendering in a React component

Hey everyone, hope you're having a great day! I've been diving into React for a few months now. I'm making an effort to steer clear of using the traditional React Components, opting instead for React Hooks. However, there are instances wher ...

Tips for managing images within the CardMedia component in React Material UI

Some specific images appear much larger and have hidden parts:https://i.stack.imgur.com/God1D.png I've managed to adjust the size somewhat by experimenting with width and height: const useStyles = makeStyles((theme) => ({ ... media: { ...

Error in ReactJS: Trying to access a property called 'maps' of an undefined value causing a TypeError with Google Map integration

While attempting to include the GeoCoder API code, I encountered an error stating "TypeError: Cannot read property 'maps' of undefined". This is the code snippet: import React from 'react'; import { compose, withProps,withHandlers } f ...

Emphasize the engaged menu selection when the page is refreshed

My application is a dashboard app built with React, Redux, and Antdesign. I utilized the layout provided by Ant design at https://ant.design/components/layout/. One issue I encountered is that when clicking on side menus, the active menu gets bold but upo ...

Having trouble with uploading images using Form.File in React?

I'm facing an issue with my React code for uploading an image. It doesn't seem to be working and I can't figure out why. Can someone please assist me? return ( <div> <FormContainer> <h1>Edit Product& ...

An issue occurred while recognizing the create-react-app, despite being duly installed

After successfully installing create-react-app, I encountered an issue when attempting to create my own app. A message stating 'create-react-app' is not recognized as an internal or external command appeared. You can see the exact error message ...

Style for Selected Avatar Chips in Flutter FilterChip

I'm using a `FilterChip` along with a `CircleAvatar` for the avatar, but when it's selected, there's an unwanted rectangle that I can't seem to locate any information about. How can I get rid of it? Here is the code snippet: child: Fi ...

Tips for effectively utilizing the Material-UI Grid component to implement this layout

Currently, I am working on incorporating this design in Material-UI by utilizing the Grid component. To better delineate the boundaries, I have marked the container border in red for clarity. The Add button should be positioned at the far right of the c ...

Is it possible to modify the appearance or behavior of a button in a React application based on its current state?

I'm looking to customize the color of a button based on different states. For example, if the state is active, the button should appear in red; otherwise it should be blue. Can anyone suggest how this can be achieved in React? Furthermore, I would als ...

React-redux: Data of the user is not being stored in redux post-login

Hello everyone, I am fairly new to using react-redux and I'm currently facing an issue with storing user information in the redux store after a user logs in. I am utilizing a django backend for this purpose. When I console out the user in app.js, it ...

Tabbed search results links

Currently, I am in the process of developing a search application and facing some challenges with implementing tabbed results links. These tabs are similar to what you see on websites like google.com/search=?user_query and bing.com/search=?user_query... wh ...

Apologies, I encountered an error message saying "npm i react-push

An error occurred while trying to install react-push-notification: Error code ERESOLVE: Unable to resolve dependency tree While resolving dependencies, the following issues were found: react@^17.0.2 from the root project Could not resolve peer depen ...

How come I am unable to save an array of objects in a State within React JS?

React JS component: When I make a request to the backend to fetch data stored in a MySQL table, it returns an array of objects. I store this data in a state called `favcoin`. However, when I console.log(favcoin), it displays an empty array [ ]. Strangely, ...

Discussing the size of windows within React Material-UI's makeStyles framework

When I create a custom style for a specific component, my const declaration typically looks like this: const useStyles = makeStyles((theme: Theme) => createStyles({ screen: { margin: 0, padding: 0 }, surface: { backgroun ...