Home > other >  How to fetch an api using axios?
How to fetch an api using axios?

Time:11-02

(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 .then in axios, use response.data for pointing to the actual data in the response.
  • useEffect will execute based on its dependency-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)
  • Related