2020-12-30

Why is data undefined from json?

I want to get the names of the cocktails through api. I brought the data. But I can't read the properties inside.

This is JSON

{
  "drinks": [
    {
      "idDrink": "12784",
      "strDrink": "Thai Iced Coffee",
      "strCategory": "Coffee / Tea",
      "strIBA": null,
      "strAlcoholic": "Non alcoholic",
      "strGlass": "Highball glass",
      "strDrinkThumb": "https://www.thecocktaildb.com/images/media/drink/rqpypv1441245650.jpg",
      "strIngredient1": "Coffee",
      "strIngredient2": "Sugar",
      "strIngredient3": "Cream",
      "strIngredient4": "Cardamom",
      "strMeasure1": "black",
      "strMeasure3": " pods\n",
      "strImageAttribution": null,
      "strCreativeCommonsConfirmed": "No",
      "dateModified": "2015-09-03 03:00:50"
    }
  ]
}

This is useFetch.jsx This file serves as a data import.

import { useState, useEffect } from "react";

function useFetch(url) {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  async function fetchUrl() {
    const response = await fetch(url);
    const json = await response.json();
    setData(json);
    setLoading(false);
  }
  useEffect(() => {
    fetchUrl();
  });
  return [data, loading];
}
export default useFetch;

This is Main.jsx This file displays the data on the screen.

import React from "react";
import styled from "styled-components";
import useFetch from "./useFetch";

const url = "https://www.thecocktaildb.com/api/json/v1/1/random.php";
const Main = () => {
  const [data, loading] = useFetch(url);
  return (
    <>
      {loading ? (
        "Loading..."
      ) : (
        <ul>
          {[data].map(
            ({ idDrink, strDrink, strAlcoholic, strGlass, strDrinkThumb }) => (
              <Container>
                <img src={`${strDrinkThumb}`} alt="" />
                <li key={`${data.idDrink}`}>{`Drink ${data.strDrink}`}</li>
              </Container>
            )
          )}
        </ul>
      )}
    </>
  );
};
export default Main;
const Container = styled.div``;

Run console.log([data]); and I can see that the data is flowing well. But the data in is undefined.



from Recent Questions - Stack Overflow https://ift.tt/3nZ93AV
https://ift.tt/eA8V8J

No comments:

Post a Comment