Nat
Nat

Reputation: 71

Uncaught TypeError: Object is not a function in fetch API result

I need to access products that is inside a result from an API fetch. I tried multiple ways but is says or that map is undefined or something else.

Here's the imagem of the json response:

enter image description here Here is action:

function getProducts(products) {
return request
    .get(process.env.API_URL + 'url')
    .send({
        products: products,
    })
    .set('Content-Type', 'application/json')
    .then((data) => console.log(data));}

Here is React component

  constructor(props) {
    super(props);
    this.state = {
      products: [],
    };
  }

  componentDidMount() {
    getProducts(this.state.products).end((err, data) => {
      if (!err) {
        this.setState({
          products: data.body[0].products,

        });
      }
    });
  }

and my map function is inside render:

render() {
    return (
      <div>
        {this.state.products.map((p, index) => (

Thanks for any advice!

Update

This is response for console.log(this.state.products)

enter image description here

Upvotes: 0

Views: 2529

Answers (3)

martinedwards
martinedwards

Reputation: 5835

I had the same error message, what I'd done wrong is destructured an import that didn't need destructuring.

import { fetch } from "isomorphic-unfetch";

Should have been

import fetch from "isomorphic-unfetch";

Not sure if this solves your issue, but thought it was worth putting it down incase it helps someone else.

Upvotes: 1

Nat
Nat

Reputation: 71

The answer for that error was to change a bit getProducts function, remove all .then:

    function getProducts(products) {
    return request
        .get(process.env.API_URL + 'url')
        .send({
            products: products,
        })
        .set('Content-Type', 'application/json')
    });  
}

Upvotes: 0

ioedeveloper
ioedeveloper

Reputation: 538

data is not returned from your getProducts function. You are just console logging it. Return data in your .then callback function.

function getProducts(products) {
    return request
        .get(process.env.API_URL + 'url')
        .send({
            products: products,
        })
        .set('Content-Type', 'application/json')
        .then((data) => {
            console.log(data);
            return data;
    });  
}

and then modify componentDidMount function to

  componentDidMount() {
    getProducts(this.state.products).end((err, data) => {
      if (!err) {
        this.setState({
          products: data.body.products,

        });
      }
    });
  }

Upvotes: 0

Related Questions