Search code examples
javascriptreactjsintellij-ideaaxioscreate-react-app

Intellij + create-react-app : axios is undefined


I'm doing my first steps with axios so far and made up the following:

import Navbar from 'react-bootstrap/Navbar';
import Form from 'react-bootstrap/Form';
import {InputGroup} from "react-bootstrap";
import axios from 'axios';

const api_key = process.env.API_KEY;

const SearchInput = () => {
    async function changeHandler(e) {
        const axios = require('axios').default;

        const url = 'https://api.thedogapi.com/v1/breeds/search?q=' + e.target.value
        const config = {
            method: 'GET',
            mode: 'cors',
            headers: {
                'x-api-key': api_key
            }
        }
        axios.get(url,config)
    }
....

Next up i was trying to run this, but i get "Uncaught (in promise) TypeError: axios is undefined"-Error.

Then I realized that import axios from 'axios' was an unused import in my JS-File up to Intellij. So I Double-Checked my Packages of course and reinstalled them also:

"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.1.3",                             <<<<< here it is
"bootstrap": "^5.2.2",
"react": "^18.2.0",
"react-bootstrap": "^2.6.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"

},

I'm asking this question as IntelliJ related because I do not have much of an idea so far if IntelliJ is part of the problem or not.


Solution

  • In your example you are using a variable axios instead of the axios module. That variable is assigned with a require call but require is not a valid way to import modules in the browser. Get rid of it and use only import statements to import modules.