React.js does not return data in the map() function

Asked

Viewed 47 times

-1

Hello, everyone. I’m a beginner in React.js and would like help with this problem: I have a service that runs some Selects on tables from an Oracle database and, with the result of these Selects, exposes such data as a list of JSON objects. Consulting the API via the browser (Chrome), I get this information: Resultado da consulta à API That is: the API is returning the data correctly. To display them on a screen in the React application, I created this component:

import React, {Component} from 'react';


export default class App extends React.Component {

  state = {
    carregando: true,
    pedidos: []
  }

  async componentDidMount() {
    const url = "http://localhost:8000/pedidos-bloqueados/";
    fetch(url)
    .then(response => {
      return response.json();
    })
    .then(d => {
      this.setState({ pedidos: [d], carregando: false });
    })
    .catch(error => console.log(error))
  }

  render() {
    return (
      <div>
        { this.state.carregando? <div>Carregando...</div> : <div><li> Cliente: * {(this.state.pedidos.map((pedido, index)=>(this.state.pedidos[index]))).map((p, i)=> p['cliente'])}</li></div> } *
      </div>
    );
  }
}

Turns out, execution of the function map() , within the method surrender() , is shown only:

Client:

Without any information. And the component cannot perform a for() in the method surrender() to iterate over the list objects in JSON, so I couldn’t see the result. My problem is in the stretch:

{ this.state.carregando? <div>Carregando...</div> : <div><li> Cliente:  {(this.state.pedidos.map((pedido, index)=>(this.state.pedidos[index]))).map((p, i)=> p['cliente'])}</li></div> }

How can I display the properties of each list object in the component ? (Note: client is only ***one of the attributes of the returned JSON object [there are others like salesman, request , etc.], but if I can list this property, I can replicate the behavior for others).

Once again, I thank you ENORMOUSLY any help !

1 answer

1

The problem is on the first map, you are returning the index of this.state.requests and not the index of the request being traveled.

I changed the map a little to make the problem more readable.

Here’s what you’re doing:

this.state.pedidos.map((pedido, index) => {
    return this.state.pedidos[index];
}))

Change to:

this.state.pedidos.map((pedido, index) => {
    return pedido[index];
}))

This will solve your problem, but you can also stop setting the this.state.requests as [d] and leave only d, this way you could remove the first map and leave only the second.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.