javascriptreact-native

How to fetch an api using axios?


(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)

Solution

  • Two changes in your code:

    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)