Using module.exports in React ES6

Steven Collins picture Steven Collins · Jul 31, 2019 · Viewed 16.6k times · Source

I am trying to use module.exports to create a 'global' function which I can use in my React project to make API calls using Axios.

I have tried the following...

import axios from 'axios';

module.exports = {
    fetchApi: function (endPoint) {
        var encodedURI = window.encodeURI('http://localhost:3001/' + endPoint);

        return axios.get(encodeURI)
            .then(function (response) {
                return response.data
            })
    }
}

//call function in other components like this
componentDidMount () {
    fetchApi.fetchApi(this.setState.endPoint)
    .then(function (endPoint) {
        console.log("API endpoint: " + endPoint)
    })
}

this returns the error... 'fetchApi' is not defined no-undef

I am aware that usually you can import and export components using export default but I thought this wasnt required if using module.export.

Also, if I try to import like this...

import fetchApi from '../../../utils/api'

I get the following error... Attempted import error: '../../../utils/api' does not contain a default export (imported as 'fetchApi').

Any help appreciated. Thanks.

Edit:

import axios from 'axios';

Solution (Edit)...

api.js

const api = {
    fetchApi: function(endPoint){
        var encodedURI = window.encodeURI('http://localhost:3001/' + endPoint);
        console.log(encodedURI)

        return axios.get(encodedURI)
            .then(function (response) {
                return response.data

            })
    }
}

export default api;

Sites.js

import api from '../../../utils/api'

    //single api call
    componentWillMount = async () => {
        api.fetchApi('sites')
            .then(data => {
                console.log(data);
                this.setState({ rows: data.rows, columns: data.columns })
            })
            .then(async () => {
                this.setState({ tableRows: this.assemblePosts(), isLoading: false })
            });
    }

This gives me access to the following api endpoint...

http://localhost:3001/sites

Thanks for your help.

Answer

tarzen chugh picture tarzen chugh · Jul 31, 2019

I would advice to not mix require and es6 import syntax. Stick with es6 syntax. Same thing with es6 syntax.

import axios from 'axios';

const helpers = {
    fetchApi: function(){

    }
}

export default helpers;

Usage

import helpers from './helpers';

helpers.fetchApi()