(https://jsonplaceholder.typicode.com/posts/5)
I'm new in react-native.
I want to know how to fetch the below api using axios in react-native.
What I am doing wrong here? I'm not able to fetch data in this way, why?
Thank You in advance!
const [data, setData] = useState([]);
useEffect(()=>{
axios.get("https://jsonplaceholder.typicode.com/posts/5")
.then((data)=> {setData(data)})
.catch((error) => console.error(error))
})
console.log(data)
CodePudding user response:
Two changes in your code:
- when using
.thenin axios, useresponse.datafor pointing to the actual data in the response. useEffectwill execute based on itsdependency-arrays, you should make sure that it is not going to re-render all the time, so, you pass a[]at the end of this hook to prevent re-rendering. (Becuase[]is an empty array which will never change!)
It may solve your problem:
const [data, setData] = useState([]);
useEffect(()=>{
axios.get("https://jsonplaceholder.typicode.com/posts/5")
.then((response)=> {setData(response.data)})
.catch((error) => console.error(error))
},[])
console.log(data)
