Search code examples
javascriptreactjsxmlapiget

Accessing a variable from outside a function - Javascript, API, XMLHttpRequest


Just wanting to access the 'data' variable from this XMLHttpRequest function. Need to use the data in my 'App' react component which is below.

I have tried making the 'let data' global? But just need to be able to access it outside of the function where the 'outside' console.log is. Currently, it shows undefined.

So asking how to make my data be accessed by my react component 'App'.

Sorry, I am new to using this function to get API data.

Thank you for the help, and if you need any more information please ask!

const request = new XMLHttpRequest()

request.open('GET', 'https://ghibliapi.herokuapp.com/films', true)

let data

request.onload = function () {
   let data = JSON.parse(this.response)

  if (request.status >= 200 && request.status < 400) {
    data.forEach((movie) => {
      console.log(movie.title)
    })
  } else {
    console.log('error')
  }
}

console.log(data,"outside")

request.send()



    class App extends Component {
        constructor(props) {
          super(props);
          this.state = {
          
          };
        }
        render() {
            return (
                <>
                    <DateRangePickerWrapper value={this.state.child1}/> 
                </>
            )
        }
    }

Solution

  • You're using class programming on your react aplication, so you must do somenthing like this

    import axios from 'axios'
    
    class App extends Component {
     constructor(props){
            super(props);
            this.state = {data: []}
    
        }
    
        componentDidMount(){
            axios.get("https://ghibliapi.herokuapp.com/films")
                .then(response =>{
                    this.setState({data: response.data});
                })
                .catch(function(error){
                    console.log(error)
                })
        }
    
        componentDidUpdate(){
            axios.get("https://ghibliapi.herokuapp.com/films")
                .then(response =>{
                    this.setState({data: response.data});
                })
                .catch(function(error){
                    console.log(error)
                })
        }
    
        
        render() {
    
           
            
            return (
                <div>
                    {data.map(data=> (
    
                    //logic to render the api's data
                    
                    ))}
                    
    
                        
                    
                </div>
    
                
            )
        }
    }