Issue
(https://jsonplaceholder.typicode.com/posts/5)
I'm new in react native. I want to know how to fetch this api using axios in react native. anyone can help me to do that.
What i am doing wrong here, i can't able to fetch using 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)
Solution
Two changes in your code:
- when using
.then
in axios, useresponse.data
for pointing to the actual data in the response. useEffect
will 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)
Answered By - Amirhossein Sefati
Answer Checked By - - Pedro (ReactFix Volunteer)