React Fetch not Fetching - javascript

In my App.js function, when it first loads, I want to fetch a website. This website contains .json data. The console gives the following error when I try to fetch the website:
App.js:9 GET https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313 net::ERR_BLOCKED_BY_CLIENT
localhost:/1 Uncaught (in promise) TypeError: Failed to fetch
App.JS:9 GET https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313 net::ERR_BLOCKED_BY_CLIENT
localhost:/1 Uncaught (in promise) TypeError: Failed to fetch
When I visit the website through the web browser, I'm able to see the JSON.
My App.js Code:
import logo from './logo.svg';
import './App.css';
import Weather from './Weather'
import React, { Component, useState } from "react";
function App() {
const [details, setDetails] = useState("0");
fetch("https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313")
.then(response => response.json())
.then((data) => {
setDetails(data)
console.log("hi")
} );
return (
<div className="App">
<div className="weatherWrap">
<Weather longg="0" lat="0" name="China"/>
</div>
</div>
);
}
export default App;
I'm assuming I'm fetching the website incorrectly. I also think that the way I did it, it will keep fetching every time. While I only want it to fetch once. Please let me know how to fix it. Thanks!

Try below piece of code:
const url = 'https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313';
function App() {
const [details, setDetails] = useState([]);
const getDetails = async()=>{
const response = await fetch(url);
const details = await response .json();
setDetails(details );
}
useEffect(() => {
getDetails();
},[]);
}

Here is the code that will work for you. Link
import "./styles.css";
import { useEffect, useState } from "react";
export default function App() {
const [details, setDetails] = useState("0");
useEffect(() => {
fetch(
"https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313"
)
.then((response) => response.json())
.then((data) => {
console.log(data);
});
}, []);
return (
<div className="App">
<div className="weatherWrap">hello world</div>
</div>
);
}

Related

Passing object as prop returns undefined in destination component ReactJS

I'm trying to pass a JSON object (id) returned from an API call to another component via props and use that object(id) to fetch more data from a different endpoint. The problem is, when i pass the prop using object literal to the api, it gives an error undefined but when i console log the object(id) it works fine. What could be the issue? Just started learning React.
component passing object as prop
import axios from "axios";
import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import Cast from "./Cast";
const DetailsView = () => {
const { id } = useParams();
const [details, setDetails] = useState([]);
useEffect(() => {
axios
.get(
`https://api.themoviedb.org/3/movie/${id}?api_key=<<api_key>>&language=en-US`
)
.then((response) => {
setDetails(response.data);
});
}, []);
return (
<div className="w-full h-[650px] text-white">
<<bunch of code>>
<Cast id={details?.id}/>
</div>
);
};
export default DetailsView;
component receiving prop
import React, { useState, useEffect } from "react";
import axios from "axios";
const Cast = (props) => {
const [cast, setCast] = useState([]);
const sid = props.id;
useEffect(() => {
axios
.get(
`https://api.themoviedb.org/3/movie/${sid}/credits?api_key=<<api_key>>&language=en-US`
)
.then((response) => {
setCast(response.data.cast);
console.log(response.data.cast);
});
}, []);
console.log(sid);
return (
<div className="absolute">
{cast && cast.map((item, index) => <p className="">{item.name}</p>)}
<p>{sid}</p>
</div>
);
};
export default Cast;
It doesn't work initially but when I edit the code, since the change is happening live, it fetches the data but when I refresh the page, Axios reports an error 404
xhr.js:220 GET https://api.themoviedb.org/3/movie/**undefined**/credits?api_key=56fbaac7fd77013cc072d285a17ec005&language=en-US 404
Your id property does not exist until the API call is completed, and there is a rerender after setDetails.
You can check if id exists and based on that render your Card component. Also, looks like details is an object not an array, so I changed the useState statement to reflect that.
import axios from "axios";
import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import Cast from "./Cast";
const DetailsView = () => {
const { id } = useParams();
const [details, setDetails] = useState({});
useEffect(() => {
axios
.get(
`https://api.themoviedb.org/3/movie/${id}?api_key=<<api_key>>&language=en-US`
)
.then((response) => {
setDetails(response.data);
});
}, []);
return (
<div className="w-full h-[650px] text-white">
<<bunch of code>>
{details?.id && <Cast id={details?.id}/>}
</div>
);
};
export default DetailsView;

Can't get image to load after connecting to an API using react.js

I've created a custom fetch component, and I'm simply trying to get an image to load on the page from an API called "the dog API". Have I missed something crucial?
App.js
import './App.css';
import './Dog.js';
import useFetch from './useFetch';
function DogApp() {
const API_KEY = "";
const { data, loading, error } = useFetch(`https://api.thedogapi.com/v1/images/search/API_KEY=${API_KEY}`);
if (loading) return <h1>Loading the dogs!</h1>
if (error)console.log(error);
return (
<div className="DogApp">
<img src={data?.url}></img>
</div>
);
}
export default DogApp;
UseFetch.js (hook for fetching the data)
import { useEffect, useState } from 'react';
import axios from "axios";
function useFetch(url) {
const [data, setData] = useState(null); //initialize as null depending on what data is
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
setLoading(true);
axios //make request, if successful it sets data, if not, seterror state
.get(url)
.then((response) => {
setData(response.data);
}).catch((err) => {
setError(err)
}).finally(() => {
setLoading(false);
});
}, [url]);
return {data, loading, error};
}
export default useFetch;
API URL I'm trying to retrieve data from : https://api.thedogapi.com/v1/images/search/
So you're API call (according to the example on thedogapi.com) requires the API key to be set in the header like so:
axios.defaults.headers.common['x-api-key'] = "DEMO-API-KEY"
That fixes the 404, but your code still won't work because the data is returned as an array of objects. So you'll need to map them like so:
{data.map((breed) => (<img src={breed?.url} />))}
I've created a demo sandbox here

i cant fetch data after deployment in react app

The app work perfectly locally. The error appears after i deploy it using firebase hosting. The code below is the component where i fetch the data from the api resource
import React, { useEffect, useState } from 'react'
import{ useSelector, useDispatch} from "react-redux"
import { setProducts } from "../containers/redux/actions/productActions"
import ProductComponent from './ProductComponent';
import axios from 'axios';
function ProductList() {
const products = useSelector((state) => state);
const dispatch = useDispatch()
const [searchValue, setSearchValue] = useState('');
const fetchProducts = async ( searchValue) => {
const response = await axios
.get(`http://www.omdbapi.com/?s=${searchValue}&apikey=??????`)
.catch((err) => {
console.log("Err", err);
});
if(response.data.Search){
dispatch(setProducts(response.data.Search));
}
};
useEffect(() => {
fetchProducts(searchValue);
// eslint-disable-next-line react-hooks/exhaustive-deps
},[searchValue]);
console.log("Products: " , products)
return (
<div className='home'>
<div className='search-box'>
<input
value={searchValue} onChange={(e) => setSearchValue(e.target.value)}
type="text"
placeholder="Search.."
>
</input>
</div>
<div className='products-list'>
<ProductComponent />
</div>
</div>
)
}
export default ProductList
Error message appears on the console of the deployed app :
ProductList.js:21 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'data')
if(response.data.Search){
dispatch(setProducts(response.data.Search));
}
Try to check your response first.
I think you may have to prove catch error here. Adding else statement in case of response.data.Search is undefined or use response?.data.Search
Most browsers will block insecure requests (http) made from secure sites (https).
Change http://www.omdbapi.com/ to https://www.omdbapi.com/

Having trouble displaying api data on the page?

Im making a project where I fetch an image of a recipe card from https://spoonacular.com and I want it displayed on my react.js app. For some reason I can't get the API data from displaying on the page when I run it. Please help Im really stuck. I keep getting the error that recipeList is undefined in Recipe.js but I thought it was defined?
This is my Home.js:
import React, { useEffect, useState } from "react";
import axios from "axios";
import Recipe from "../components/Recipes";
const URL = `https://api.spoonacular.com/recipes/716429/information?apiKey=${APIKey}&includeNutrition=false`;
function Home() {
const [food, setFood] = useState();
useEffect(() => {
if (food) {
axios
.get(URL)
.then(function (response) {
const recipeList = response.data;
setFood(recipeList);
})
.catch(function (error) {
console.warn(error);
});
}
}, [food]);
return (
<main>
<Recipe recipeList={food} />
</main>
);
}
export default Home;
this is my Recipe.js
import React from "react";
function Recipe({ recipeList }) {
return (
<div className="Recipe">
<div>{recipeList.title}</div>
<img src={recipeList.image} />
</div>
);
}
export default Recipe;
you need initializing empty
const [food, setFood] = useState({});
and in useEffect evaluate if food is empty
useEffect(() => {
const getData=()=>{
axios
.get(URL)
.then(function (response) {
const {data} = response;
setFood(data);
})
.catch(function (error) {
console.warn(error);
});
}
if(!food){ // validate if food is empthy to get data (food)
getData()
}
}, []); // here is not necesary use food, because never happen anything with that variable
The response example can be seen here.
To call that using axios:
import React, { useEffect, useState } from "react";
import axios from "axios";
import Recipe from "../components/Recipes";
const URL = `https://api.spoonacular.com/recipes/716429/information?apiKey=${APIKey}&includeNutrition=false`;
function Home() {
const [food, setFood] = useState({});
useEffect(() => {
// You can add any if-else statement here
// but you can also do the fetch without it
axios
.get(URL)
.then(function (response) {
setFood(response.data);
})
.catch(function (error) {
console.warn(error);
});
}, []);
return (
<main>
<Recipe recipeList={food} />
</main>
);
}
export default Home;
And based on the response, your Recipe.js should working properly.

Trying to fetch APi but it is not displaying the data

I have created Context API I am trying to fetch the data from my API so I can use the state globally, but is not doing it. I am not getting any errors in the console. But when I try to fetch from the Other Component, I am getting data in the console. Just in the Context, I am not getting it.
import React, {useState, useEffect}from 'react'
import ITrucks from '../interface/truck';
import axios from 'axios';
export const TrucksContext= React.createContext({})
export const TrucksProvider:React.FC = ({ children } ) => {
const [isLoading, setIsLoading] = useState(false);
const [trucks, setTrucks] =useState<ITrucks[]>([])
const [isError, setIsError] = useState(false);
const fetchData = () => {
axios
.get('https://localhost:7000/trucks')
.then((response) => {
setIsLoading(false);
setTrucks(response.data);
console.log(response.data)
})
.catch((error) => {
setIsLoading(false);
setIsError(true);
console.log(error);
});
};
useEffect(() => {
fetchData();
}, []);
return (
<TrucksContext.Provider
value={{trucks}}
>
<>
{children}
</>
</TrucksContext.Provider>
);
}
try setTrucks([...response.data])
The problem could be in the API itself. When an API has an error it often return empty data to Axios instead of an error, it depends on the return statement

Categories

Resources