0
votes

I'm having problems with this simple api call in react native and I have no idea why. I did exactly the same thing on reactJs and it worked on the browser perfectly.

const FlatListGames = ({ navigation }) => {

 const [games,setGames] = useState([]);


 useEffect(() => {
    function fetchAPI(){
      axios.get('http://127.0.0.1:5000')
        .then(response => {
            setGames(response.data)
        })
        .then(error => console.log(error));
    }
    fetchAPI();
 }, [])

 console.log(games);

[Unhandled promise rejection: Error: Network Error]

  • node_modules/axios/lib/core/enhanceError.js:24:11 in error.toJSON
  • node_modules/axios/lib/adapters/xhr.js:114:23 in dispatchXhrRequest
  • node_modules/event-target-shim/dist/event-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent
  • node_modules/react-native/Libraries/Network/XMLHttpRequest.js:575:10 in setReadyState
  • node_modules/react-native/Libraries/Network/XMLHttpRequest.js:389:6 in __didCompleteResponse
  • node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:189:10 in emit
  • node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:425:19 in __callFunction
  • node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:112:6 in __guard$argument_0
  • node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:373:10 in __guard
  • node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:4 in callFunctionReturnFlushedQueue
  • [native code]:null in callFunctionReturnFlushedQueue
1

1 Answers

-1
votes

this is happening because you are not using .catch, rather you are using .then. .then is used for when a promise is resloved successfully, and .catch is used for when error is occured, so you need to replace the second then with catch.

const FlatListGames = ({ navigation }) => {

 const [games,setGames] = useState([]);


 useEffect(() => {
    function fetchAPI(){
      axios.get('http://127.0.0.1:5000')
        .then(response => {
            setGames(response.data)
        })
        .catch(error => console.log(error));
    }
    fetchAPI();
 }, [])

 console.log(games