Axios data being returned, but calling code not working

1.4k Views Asked by At

Thanks in advance for reading. I am realtively new to the react and es6 world. I had a working component that used axios to call an api. All good. Re-engineered it to put redundant api call code into a utils and call it from anywhere that needs data. But I cannot figure out why this function call isn't working. Anyone see what I am missing?

Here is the utility function:

import Axios from 'axios';

export function getData(strPath){
    var sendToken = {
      headers: {'Authorization': 'Token tokenHere'}
    };
    var sendPath = "http://pathHere.com/api/" + strPath

  Axios
    .get(sendPath,sendToken)

    .catch(function (error) {
      //error handling here
      })
    .then(function (response) {
      console.log(response.data.results) //outputs my array of 2 elements
      return(response.data.results);
    })
};

Here is the calling react component:

import React, { Component } from 'react';
import { getData } from './Utils';

class BoardContainer extends React.Component {
  constructor(props){
    super(props);
    this.state = { positions: [] };
  }

  componentWillMount(){
    var x = getData('positions');  //simplified code for debugging and example
    console.log(x);  //ISSUE: x is undefined
  }

  render() {
    return(
      <div>Testing Rendering Board Container
        //rendering code would be here (child component call)
      </div>
    )
  }
} 
1

There are 1 best solutions below

1
On BEST ANSWER

Utility:

import Axios from 'axios'

export function getData(strPath){
    const sendToken = {
      headers: {'Authorization': 'Token tokenHere'}
    }
    const sendPath = "http://pathHere.com/api/" + strPath
    return Axios.get(sendPath, sendToken)    
};

Component:

import React, { Component } from 'react'
import { getData } from './Utils'

class BoardContainer extends React.Component {
  constructor(props){
    super(props);
    this.state = { positions: [] }
  }

  componentWillMount(){
    getData('positions').then((response) => {
        console.log(response)
    }).catch((error) => {
        console.log(error)
    })     
  }

  render() {
    return(
      <div>Testing Rendering Board Container
        //rendering code would be here (child component call)
      </div>
    )
  }
}