Am new to react, I have a fetch operation and I want to check data from api using console.log before using it just like in javascript but i can't figure out how to do it in react...Any help?
const [all, setAll]=React.useState([])
React.useEffect(()=>{
fetch('https://api.themoviedb.org/3/trending/all/day?api_key=key')
.then(data=>{
return data.json()
}).then(completedata=>{
setAll(completedata)
})
.catch((err) => {
console.log(err.message);
})
},[1])
console.log(all)
CodePudding user response:
It's all still Javascipt, use console.log(completedata)
in the promise chain, or the all
state in an useEffect
hook with dependency on the all
state.
const [all, setAll] = React.useState([]);
React.useEffect(()=>{
fetch('https://api.themoviedb.org/3/trending/all/day?api_key=key')
.then(data => {
return data.json();
})
.then(completedata => {
setAll(completedata);
console.log(completedata)
})
.catch((err) => {
console.log(err.message);
});
},[]);
or
const [all, setAll] = React.useState([]);
useEffect(() => {
console.log(all);
}, [all]);
CodePudding user response:
You can use like as in javascript:
}).then(completedata=>{
setAll(completedata)
console.log("your complete data is here" JSON.stringify(completedata))
})
CodePudding user response:
import {useState,useEffect} from 'react';
const [all, setAll] = useState([]);
useEffect(()=>{
fetDataFromApi()
},[]);
const fetDataFromApi = async () => {
const data = await fetch('https://api.themoviedb.org/3/trending/all/day?api_key=key')
const movies = data.json();
if(movies.error){
console.log('error -> ',movies.error)
else{
setAll(movies.results)
}
}
}
return(
<>
{JSON.stringify(all)}
</>
)