0

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;

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Try:

const [companies, setData] = useState()

instead of

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

1 Comment

Please explain why this change may improve the OP's outcome.
1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.