AnonAnon
AnonAnon

Reputation: 15

React: Getting undefined using async function

I got the last question closed as duplicate... I'm clearly using async/await

I'm trying to fetch data from api and pass it to state, companies is array of object and I'm getting error undefined of id at <p>{companies ? console.log(companies[0].id) : ""}</p> and I cant figure out why

import './App.css';
import React, { useState, useEffect } from "react";
import Navigation from './Components/Navigation'
import axios from 'axios'


const App = () => {


  const [companies, setData] = useState({});

  async function fetchData() {
    const urlcompanies = "http://localhost:8000/data-companies/";
    const response = await fetch(urlcompanies);
    const data = await response.json();
    setData(data)  
  }

  useEffect(() => {
   fetchData(); 
  }, [])

  
    

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
         <p>{companies ? console.log(companies[0].id) : ""}</p>
         <Navigation companydata = {companies} /> 
        <a
        
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

Upvotes: 0

Views: 865

Answers (3)

Adel Stiti
Adel Stiti

Reputation: 58

Update initial state

const [companies, setData] = useState({});

to

const [companies, setData] = useState([]);

and change this

<p>{companies ? console.log(companies[0].id) : ""}</p>

to this

<p>{companies.length ? console.log(companies[0].id) : ""}</p>

Upvotes: 1

jcklopp
jcklopp

Reputation: 491

Try:

const [companies, setData] = useState()

instead of

const [companies, setData] = useState({})

Upvotes: 1

codemonkey
codemonkey

Reputation: 7905

Change this

const [companies, setData] = useState({});

to

const [companies, setData] = useState(null);

Otherwise, on first render you're trying to access the first element of what you assume will be an array, which does not get set until after you call that async function.

This

{companies ? console.log(companies[0].id) : ""}

Will print "" on first render, and then, once you set your companies variable to an actual array, you will see the id of your first element.

Upvotes: 1

Related Questions