React NOOB issue I'm having:
I have a JSX file that uses Axios to make an API call:
fetch-api-data.jsx:
import * as axios from 'axios';
export class FetchApiData {
  constructor() {
    console.log('FetchAPIData loaded');
  }
  shareMyStoryData(URL) {
    return axios.get(URL)
    .then(function (response) {
      console.log(response.data);
    })
    .catch(function (error) {
      console.log(error);
    });
  }
}
I have a component that references that API call:
share-my-story.jsx
import * as React from 'react';
import * as DOM from 'react-dom';
import PropTypes from 'prop-types';
import './share-my-story.scss';
import FetchApiData from './fetch-api-data';
class ShareMyStory extends React.Component {
  componentDidMount() {
    const URL = '/js/feed/sms.json';
    const smsData = FetchApiData.shareMyStoryData(URL);
    console.log('shareMyStory.jsx - componentDidMount: load: ' + URL);
  }
  render() {
      return (
          <div className="item">
            <h3>{headline}</h3>
            <h4>{name}</h4>
            <p>{link}</p>
          </div>
      );
  }
}
ShareMyStory.propTypes = {
  name: PropTypes.string,
  headline: PropTypes.string,
  link: PropTypes.string,
}
DOM.render(
    <ShareMyStory/>, document.getElementById('share-my-story'));
However, when webpack compiles the items and they are run in the browser, I get the following error:
TypeError: Cannot read property 'shareMyStoryData' of undefined
Is there some reason why the shareMyStoryData() method isn't available in the share-my-story.jsx file? Both of the files are in the same folder, and I can see that both the fetch-api-data.jsx and share-my-story.jsx file are getting properly bundled together in my bundle.js file.
You have 3 problems in your fetch-api-data.jsx:
export default instead of export.constructor method.shareMyStoryData class method but used it without creating a class instance. Maybe it should be static?Check out the fixed example:
import * as axios from 'axios';
export default class FetchApiData {
  constructor() {
    console.log('FetchAPIData loaded');
  }
  static shareMyStoryData(URL) {
    return axios.get(URL)
    .then(function (response) {
      console.log(response.data);
    })
    .catch(function (error) {
      console.log(error);
    });
  }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With