Search code examples
reactjsapiaxiosreact-hooksuse-effect

React axios api call error: Uncaught (in promise) TypeError: setTempFetch is not a function


When trying to load fetched data via axios in React, I get an error saying that the hook function to set my state does not exist. Is this because I used useEffect and maybe I cannot change state in useEffect?

Not sure what is wrong in code:

const {tempFetch, setTempFetch} = useState("Test load")

useEffect(()=> {
    fetchData()
}, [])


const fetchData = async () => {
    
    const config = {
        method: 'get',
        url: 'http://127.0.0.1:8000/api/states/',
        headers: {
                'Authorization': 'Basic amludHc6cG9rZW1vbmRwMjAxMkhQMTI1Mw=='
        } 
    }

    let response = await axios(config)
    let data = await response.data
    console.log("data:",data)
    setTempFetch(data)
}

Solution

  • useState hook returns array or two element. First one is the value, Second one is the handler to set value.

    I can see you have declared useState return value as object

    const {tempFetch, setTempFetch} = useState("Test load")
    

    It should be like this:

    const [tempFetch, setTempFetch] = useState("Test load")