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)
It's all still Javascipt, use console.log(data.results)
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(data => {
setAll(data.results);
console.log(data.results);
})
.catch((err) => {
console.log(err.message);
});
},[]);
or
const [all, setAll] = React.useState([]);
useEffect(() => {
console.log(all);
}, [all]);
You can use like as in javascript:
}).then(completedata=>{
setAll(completedata)
console.log("your complete data is here"+JSON.stringify(completedata))
})
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)} </> )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.