skip to Main Content
import "./App.css";
import axios from "axios";
import { useEffect, useState } from "react";

export default function Events() {
  const [data, setdata] = useState(null);
  useEffect(() => {
    axios.get("https://app.ticketmaster.com/discovery/v2/events?apikey=AZAG8m4u5gq5HgkyYk0sdE9eAG32vGPT&locale=*")
    .then((res) => {
      setdata(res.data);
    })
    .catch((error) => {
      console.log("Error encountered", error);
    });
  });
//   console.log(data);
  return (
    <div className="App">
    {/* {data._embedded.events.map((e) => {
      <li>[{e}] {e.name}</li>;
    })} */}
    <h1>In Homepage</h1>
    
  );
}

I am getting null twice before displaying the actual data:

I am getting null twice before displaying the actual data

I am trying to get data from an API and displaying it using AXIOS, but the rest of code executes once before my AXIOS request is completed.

2

Answers


  1. You need to use empty array in useEffect().

    useEffect(()=>{
    //axios request
    },[]);
    

    See https://react.dev/reference/react/useEffect#specifying-reactive-dependencies for more details on this

    Login or Signup to reply.
  2. First, you need to add an empty array to your useEffect to make it run just once.

    And you can use the && operator to render the events when they are available, like this:

    useEffect(()=>{
      // your axios code
    }, []);  // <- add the empty array here
    
    return (
      <div className="App">
        {data && data._embedded.events.map((e) => (
          <li key={e.id}>{e.name}</li>
        )}
      </div>
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search