skip to Main Content

I’m trying to get data from an url with axios but my app is stuck on loading screen like this:

Photo of the problem

code of the fetch request:

import axios from 'axios'
import {useState,useEffect} from 'react'

function useFetch(url){

    const[loading,setLoading] = useState(true)
    const[data, setData] = useState([])
    const[error, setError] = useState(null)

    const fetchData = async () => {
        try{

            const {data: responseData} = await axios.get(url)
            setData(responseData)
            setLoading(false)

        }catch(err){    
            setError(err.message)
            setLoading(false)
        }
    }

    useEffect(() => {fetchData()},[])
    return{loading,data,error}
}

export default useFetch

how I import fetch:

const {loading,data,error} = useFetch("https://fakestoreapi.com/products")

The same code worked before but it’s not working anymore. Any help is appreciated.

I tried reseting caches but it didn’t help either.

2

Answers


  1. check my simple snack to see which difference to you
    https://snack.expo.dev/@fukemy/upbeat-scones

    Login or Signup to reply.
  2. import axios from 'axios'
    import {useState,useEffect} from 'react'
    
    function useFetch(url){
    
        const[loading,setLoading] = useState(false)
        const[data, setData] = useState([])
        const[error, setError] = useState(null)
    
        const fetchData = async () => {
            try{
                setLoading(true)
                const {data: responseData} = await axios.get(url)
                if(responseData){
                  setData(responseData)
                  setLoading(false)
                }
    
            }catch(err){    
                setError(err.message)
                setLoading(false)
            }
        }
    
        useEffect(() => {fetchData()},[])
        return{loading,data,error}
    }
    
    export default useFetch
    

    As this the function call while importing this will make the loading state by default true instead try this make the loading state true inside the fetch data and also make sure the url path is correct and connection.

    https://axios-http.com/docs/res_schema axios documentation

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search