Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble Loading Method in React Component

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.

like image 431
TWLATL Avatar asked Nov 08 '22 17:11

TWLATL


1 Answers

You have 3 problems in your fetch-api-data.jsx:

  1. You should you export default instead of export.
  2. You made the spelling mistake in constructor method.
  3. You added 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);
    });
  }
}
like image 159
sergdenisov Avatar answered Nov 14 '22 22:11

sergdenisov