I have created an async API fetch in a particular .JS file. I then called it from another JS file using so that I can console.log it. (Is there a more efficient way to do this?)
Now I want to use the response objects fields from the API call above as feeder information into my HTML in my APP.JS. What would be the best way to go about that?
I was hoping to use data.[response object key] to get the response object value but that is not working.
I am looking for the most efficient way of calling an async fetch in one .JS file, importing it into another and using the response object key properties to output there values to my HTML. Is creating a hook that runs the fetch and returns the result then exporting that hook value into my app.js the best way to go?
My rfc that actually fetches the data below
import React from "react";
export default async function APIrequests() {
const response = await fetch(
`http://www.omdbapi.com/?t=Batman&y=2022&apikey=randomkey`
);
const movie = await response.json();
// console.log(movie.Title);
return movie;
}
useFetch Hook that parses the data out of my response ,,,
import React from "react";
import APIrequests from "./APIrequests";
async function mygettingdata() {
const response = await APIrequests();
console.log(response);
}
export default function useFetch() {
const { data } = mygettingdata();
return { data };
My app.js Below where I try to call the title property of the response object
import APIrequests from "./APIrequests";
import useFetch from "./useFetch";
function App() {
// const myapicall = useEffect(() => {
// async function fetchData() {
// const response = await APIrequests();
// console.log(response.Actors);
// }
// fetchData();
// }, []);
const { data } = useFetch();
return (
<div>
<h1>{data.Title}</h1>
CodePudding user response:
There are a few ways to approach this. There isn't an actual 'optimal' way of doing something that simple. It doesn't actually matter whether you import the request or you write it on the fly. The only difference would be an extra file in your project and a more organized structure. If you are really looking for something optimal check the react-query library which is a react optimized abstraction for network request with all the bells and whistles that you would probably want (caching, retries, useEffect-like fetches etc.). If you want to go with the native fetch API then you would probably want to write your request inside a useEffect like so
useEffect(() => {
//IIFE cause effects can't be async
(async () => {
try{
let response = await fetch(`http://www.omdbapi.com/?t=Batman&y=2022&apikey=randomkey`)
let json = await response.json()
//you have access to response.status here for error handling
//do something with the json data here
}catch(err){
console.error(err.message)
}
})()
},
//eslint-disable-next-line react-hooks/exhaustive-deps
[])
If you want your effect to run more than once, remove this //eslint-disable-next-line react-hooks/exhaustive-deps and add the necessary dependencies in your dependency array
CodePudding user response:
You are doing this wrong, mygettingdata
is an async so you have too wait for it to load.
See below how you could solve this
export default function useFetch() {
const [data, setData] = useState()
useEfeect(() => {
mygettingdata().then(x => {
setData(x.data)
})
}, [])
return data;
}
And then
function App() {
const data = useFetch();
return (
<div>
<h1>{data?.Title}</h1>
....