Search code examples
typescriptdatabaseaxios

Display data from state with React Typescript


I managed to get data from api with axios and locate it in react state but can't figure it out how to display it in web to be able to list whole data that im getting from my api get request. I have tried map function etc but every time it's not displaying or showing error.

below is my code and data that i managed to get from 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 InqueriesData = response.data
        console.log(InqueriesData)
        getInqueries(InqueriesData)
      })
  }, [])
  console.log(inqueries)
  return (
    <>
      <div>
        {this.state.inqueries.map(({ name }: any) => {
          return <p>{name}</p>
        })}
      </div>
    </>
  )
}

export default AdministrationPanel

My data response in console

My app state data

I was trying every solution that I managed to find but since im totally new to programming I cannot solve it.


Solution

  • Due to the absence of a token, I can't surely say that this is the final solution, maybe your response type will be different, however, the issue is that you are accessing inqueries incorrectly. You shouldn't use this.state, because you are using a function component, which has no this.state. To fix the issue you should directly use the inqueries variable as follows:

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

    Also, I would advise you to rename getInqueries to setInqueries, since it is just setting the state not getting