0
votes

Hello I have the following error when trying to consume my api

TypeError: api.get is not a function

api.js

import axios from 'axios';

const api = axios.create({ baseURL: 'http://localhost:8000', });

export default api;

action fetch:

const api = require('../../services/api');

export function productsError(bool) {
    return {
        type: 'PRODUCTS_HAS_ERRORED',
        hasErrored: bool
    };
}
export function productsIsLoading(bool) {
    return {
        type: 'PRODUCTS_IS_LOADING',
        isLoading: bool
    };
}
export function productsFetchSuccess(products) {
    return {
        type: 'PRODUCTS_SUCCESS',
        products
    };
}

export function errorAfterFiveSeconds() {
    // We return a function instead of an action object
    return (dispatch) => {
        setTimeout(() => {
            // This function is able to dispatch other action creators
            dispatch(productsError(true));
        }, 5000);
    };
}

export function ProductsFetchData() {
    return (dispatch) => {
        dispatch(productsIsLoading(true));
        api.get('/products')
            .then((response) => {
                if (!response.ok) {
                    throw Error(response.statusText);
                }
                dispatch(productsIsLoading(false));
                return response;
            })
            .then((response) => response.json())
            .then((products) => dispatch(productsFetchSuccess(products)))
            .catch(() => dispatch(productsError(true)));
    };
}

reducer fetch

export function ProductsHasErrored(state = false, action) {
    switch (action.type) {
        case 'PRODUCTS_HAS_ERRORED':
            return action.hasErrored;
        default:
            return state;
    }
}
export function ProductsIsLoading(state = false, action) {
    switch (action.type) {
        case 'PRODUCTS_IS_LOADING':
            return action.isLoading;
        default:
            return state;
    }
}
            return action.products;
        default:
            return state;
    }
}         return action.products;
        default:
            return state;
    }
}export function Products(state = [], action) {
            return action.products;
        default:
            return state;
    }
}         return action.products;
        default:
            return state;
    }
}

my store :

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

export default function configureStore(initialState) {
    return createStore(
        rootReducer,
        initialState,
        applyMiddleware(thunk)
    );
}

in my app:

import React, { Component } from 'react'
import {connect} from 'react-redux'
import { bindActionCreators } from 'redux';
import { ProductsFetchData } from '../../store/actions/productsFetch';
class index extends Component {

  componentDidMount() {
    this.props.fetchData('/products');
  }


  render() {
    if (this.props.hasErrored) {
          return <p>Sorry! There was an error loading the items</p>;
    }

    if (this.props.isLoading) {
          return <p>Loading…</p>;
    }
    return (
      <div>

      </div>
    )
  }
}

const mapStateToProps = (state) => {
  return {
      products: state.products,
      hasErrored: state.itemsHasErrored,
      isLoading: state.itemsIsLoading
  };
};
const mapDispatchToProps = (dispatch) => {
  return {
      fetchData: () => dispatch(ProductsFetchData())
  };
};
export default connect(mapStateToProps, mapDispatchToProps)(index);

basically I have error in this function:

export function ProductsFetchData() {
    return (dispatch) => {
        dispatch(productsIsLoading(true));
        api.get('/products')
            .then((response) => {
                if (!response.ok) {
                    throw Error(response.statusText);
                }
                dispatch(productsIsLoading(false));
                return response;
            })
            .then((response) => response.json())
            .then((products) => dispatch(productsFetchSuccess(products)))
            .catch(() => dispatch(productsError(true)));
    };
}

I don't know why or where I went wrong to get this error

3

3 Answers

1
votes

in action fetch, you should be change:

const api = require('../../services/api');

to:

const api = require('../../services/api').default; 

or

import api from '../../services/api')
1
votes

You should just export the baseURL as as const, then in your actions:

import axios from 'axios'
//othercode here 
export function ProductsFetchData() {
    return (dispatch) => {
        dispatch(productsIsLoading(true));
        api.get(`${}/products`)
            .then((response) => {
                if (!response.ok) {
                    throw Error(response.statusText);
                }
                dispatch(productsIsLoading(false));
                return response;
            })
            .then((response) => response.json())
            .then((products) => dispatch(productsFetchSuccess(products)))
            .catch(() => dispatch(productsError(true)));
    };
}
1
votes

When you use export default, This file will create an object with key is default and export them.

const a = 2;
export default a;

import with require:

const a = require(...)
console.log(a)
// a here will be an object
>> Object {default: 2}

So when you want to use require from export default, you have to access to .default: console.log(a.default).

Or you can use import in ES6 like this:

import a from '...';
// console.log(a)
>> 2