Show information from the state using React and Typescript

I successfully retrieved data from an API using axios and stored it in the state of my React component. However, I am struggling to display this data on the web so that I can list all the information obtained from the API request. I have tried using the map function, but I keep encountering errors or nothing is being displayed.

Below you will find my code snippet along with the data fetched from the server:

import axios from "axios"
import React, { useState, useEffect } from "react"

function AdministrationPanel() {
  const [inqueries, getInqueries] = useState<any[]>([])
  const token ="**************************************************"
  const url = "https://strapi-km.herokuapp.com/api/inquiries?populate=*"

  useEffect(() => {
    axios
      .get(url, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      })
      .then((response) => {
        const inquiriesData = response.data
        console.log(inquiriesData)
        getInqueries(inquiriesData)
      })
  }, [])
  console.log(inqueries)
  return (
    <>
      <div>
        {this.state.inqueries.map(({ name }: any) => {
          return <p>{name}</p>
        })}
      </div>
    </>
  )
}
export default AdministrationPanel

Console screenshot of data response

Screenshot of application state data

Despite trying various solutions found online, I am still unable to resolve this issue as a newcomer to programming.

Answer №1

Without a token, I cannot confirm if this is the final solution. Your response type may vary, but the issue lies in how you are accessing inqueries. Avoid using this.state in a function component, as it does not have this.state. To correct this, directly utilize the inqueries variable like so:

 <div>
        {inqueries.map(({ name }: any) => {
          return <p>{name}</p>
        })}
 </div>

Furthermore, consider renaming getInqueries to setInqueries, since it only sets the state and does not get it.

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

Error encountered: AxiosError - Request unsuccessful with status code 401 in next.js

My current project uses Next.js, and I've implemented an Axios interceptor to catch rejected promises. However, when there is a server-specific error that requires my attention, Next.js displays the error like this: https://i.sstatic.net/HHhD2.png B ...

Error: Your call to the "useFormState" function does not match any available

I am fairly new to web application development and I'm facing an issue with the useFormState function. I am currently working on building an edit form for database entries, but the code that previously worked is now throwing an error stating that ther ...

Obtain the type parameter in Typescript

In my code, I have created a simple IFactory<OUT> interface along with two classes that implement it. export interface IFactory<OUT = any> { create(): OUT; } // number implementation export class NumberFactory implements IFactory<number ...

Typescript custom react hook - toggling with useToggle

I developed a custom hook to toggle boolean values: import { useState } from 'react'; export function useToggle(initialValue: boolean) { const [value, setValue] = useState<boolean>(initialValue); const toggleValue = () => setValue ...

Exploring the use of a customizable decorator in Typescript for improved typing

Currently, I am in the process of creating TypeScript typings for a JavaScript library. One specific requirement is to define an optional callable decorator: @model class User {} @model() class User {} @model('User') class User {} I attempted ...

Parsing of the module has failed due to the presence of an unexpected character '' while attempting to import a video file

Trying to create a video player in NextJS using TS. I brought in a video file from my src/assets folder and encountered an error. Error - ./src/assets/video.mp4 Module parse failed: Unexpected character '' (1:0) You may need an appropriate load ...

Table for Django template with double entry SQL structure

In my Django application, I have the following models: from django.contrib.auth.models import User class Poll(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User) class Choice(models.Model): poll = models. ...

The modal popup feature is dysfunctional within the hierarchical component structure of angular-bootstrap-md

In my project, there is a structured hierarchy of components that includes: Agent task-list (utilizing the shared task-list-table component) task-type (as a separate component) preview-task (a modal component) agent.component.html (where task-type, ta ...

Angular offers pre-determined values that cannot be altered, known as "

I am currently learning Angular and TypeScript, and I came across a task where I need to create an object or something similar that allows me to define a readable but not editable attribute. In Java, I would have achieved this by doing the following: publ ...

What are the steps for importing KnockOut 4 in TypeScript?

It appears straightforward since the same code functions well in a simple JS file and provides autocompletion for the ko variable's members. Here is the TypeScript code snippet: // both of the following import lines result in: `ko` undefined // impo ...

Is it necessary for TrackBy to be a function in Angular 2, or can it be undefined?

Struggling with an error while developing a demo app in Angular 2. The error message reads: core.umd.js:3491 EXCEPTION: Uncaught (in promise): Error: Error in security.component.html:35:72 caused by: trackBy must be a function, but received undefined. Err ...

Understanding and processing HTML strings in typescript

I am currently utilizing TypeScript. Within my code, there is an object named "Reason" where all variables are defined as strings: value, display, dataType, and label. Reason = { value: '<ul><li>list item 1</li><li&g ...

The Ionic 2 application encountering issues with building after the installation of the Facebook login plugin

Currently, I am in the process of developing a Hybrid app using Ionic-2 on Ubuntu. I encountered an issue when trying to add Facebook login functionality to my app. After installing the Facebook plugin, the app build fails. However, if I remove the Faceb ...

Trying to access a private or protected member 'something' on a type parameter in Typescript is not permitted

class AnotherClass<U extends number> { protected anotherMethod(): void { } protected anotherOtherMethod(): ReturnType<this["anotherMethod"]> { // Private or protected member 'anotherMethod' cannot be accessed on a type para ...

Is there a solution to resolve CORS API requests between a Laravel backend and a Node.js/Express.js client?

While developing an API in nodejs/expressjs, I successfully tested it using Postman. However, when attempting to test it with an axios call within Laravel, I encountered some issues. The errors that I received are as follows: Access to XMLHttpRequest a ...

What steps can be taken to resolve the error message "How can you repair 'Cannot read properties of undefined (reading 'front_default')'?"

I'm encountering an issue while trying to display data from an API. Although I am able to access the data, a perplexing error keeps popping up that I can't seem to troubleshoot. Here's the error message: Uncaught TypeError: Cannot read pr ...

The script type `(close: any) => Element` cannot be assigned to type `ReactNode`

Encountering a problem while adding a popup in my TypeScript code Error: Type '(close: any) => Element' is not compatible with type 'ReactNode'. <Popup trigger={ <button className="fixed bott ...

The while-loop using Regex adds only a single value to my array

Within my variable htmlContent, there lies a string filled with properly formatted HTML code, which includes various img tags. The goal is to extract each value from the src attribute of these images and place them all in an array named srcList. The issu ...

Can you explain the significance of the "type" reserved word in TypeScript?

When attempting to construct an interface in TypeScript, I discovered that the word "type" is both a keyword and a reserved term. In Visual Studio 2013 with TypeScript 1.4, for instance, when defining the following interface: interface IExampleInterface { ...

Is it possible to devise a universal click handler in TypeScript that will consistently execute after all other click handlers?

In my ReactJS based application written in TypeScript, we have implemented various click handlers. Different teams contribute to the application and can add their own handlers as well. The challenge we face is ensuring that a specific global click handler ...