Lekanda
Lekanda

Reputation: 49

Failed to iterate data with React

It is my first contact with REACT. Trying to iterate a JSON in react tells me that .map is not a function.

My iterator code is:

import React, { useEffect, useState, Fragment } from 'react';
// Importar cliente Axios
import clienteAxios from '../../config/axios';


    function Clientes () {

        const [clientes, guardarClientes] = useState([]);

        const consultarAPI = async() => {
            // console.log('Consultando...');
            const clientesConsulta = await clienteAxios.get('/clientes');
            // console.log(clientesConsulta.data);

            // Colocar el resultado en el State
            guardarClientes(clientesConsulta.data);
        }

        //  Use effect es similar a componentdidmount y willmount
        useEffect( () => {
            consultarAPI();
        },[]);

        return (
            <Fragment>
                <h2>Clientes</h2>
                {console.log(clientes)}


                <ul className="listado-clientes">
                    {clientes.map(cliente => {
                       console.log(clientes)
                })}
                </ul>
            </Fragment>
        )
    }

    export default Clientes;

The resul in console is a Array of Objetcs

clientes": [
        {
            "_id": "5edd409674d46d3570b34e69",
            "nombre": "jon",
            "apellido": "perex",
            "empresa": "Leka.NET",
            "email": "[email protected]",
            "telefono": "782555555",
            "__v": 0
        },

With clientesConsulta.data console:

__proto__: Object

    __proto__: Object

    clientes: Array(5)}
       clientes: (5) [{…}, {…}, {…}, {…}, {…}]
       __proto__: Object
    clientes: Array(5)}
       clientes: (5) [{…}, {…}, {…}, {…}, {…}]
       __proto__: Object

With clientesConsulta.data.clientes console:

[{…}, {…}, {…}, {…}, {…}]

Up to this point the data enters well, it is verified. The flaw is that I don't know how to iterate. Thank you very much in advance

Upvotes: 0

Views: 76

Answers (3)

Lekanda
Lekanda

Reputation: 49

Hello and thanks to all who have intervened in the doubt. I already have the answer. I put down the code of the solution. It was to get the iterator to an external function and also as Pirhan said, it was necessary to take the data in saveClients (clientsConsult.data.clients);. The code is:

import React, { useEffect, useState, Fragment } from 'react';
// Importar cliente Axios
import clienteAxios from '../../config/axios';


function Clientes () {
    // Trabajar con el State
    // clientes = State
    // guardarClientes = Funcion para guardar el State
    const [clientes, guardarClientes] = useState({});
    //Query a la API
    const consultarAPI = async() => {
        // console.log('Consultando...');
        const clientesConsulta = await clienteAxios.get('/clientes');
        // console.log(clientesConsulta.data.clientes);

        // Colocar el resultado en el State
        guardarClientes(clientesConsulta.data.clientes);
    }

    //  Use effect es similar a componentdidmount y willmount
    useEffect( () => {
        consultarAPI();
    }, [] );


    function createArray(clientes) {
        if (clientes && clientes.length > 0) {
          return clientes.map(cliente => console.log('hola')
          );
        }
        return [];
      }

    return (
        <Fragment>
            <h2>Clientes</h2>
            {/* {console.log(clientes)} */}
            {/* {console.log(guardarClientes)} */}

            <ul className="listado-clientes">
                {createArray(clientes)}
            </ul>
        </Fragment>
    )
}

export default Clientes;

Once again thanks to those of you who have intervened and especially to user177767 who has put me on the track. Cheers

Upvotes: 1

Pirhan
Pirhan

Reputation: 186

It looks like you forgot to add ".clientes" at the end of guardarClientes(clientesConsulta.data);. It looks like it should be guardarClientes(clientesConsulta.data.clientes); Is this the case?

Upvotes: 1

AttemptedMastery
AttemptedMastery

Reputation: 768

Since it is an asynchronous call and you are iterating within the return, set a conditional to make sure the data has actually been set to state like so:

        return (
            <Fragment>
                <h2>Clientes</h2>
                {console.log(clientes)}


                <ul className="listado-clientes">
                    {clientes ? clientes.map(cliente => {
                       console.log(clientes)
                }) : ''}
                </ul>
            </Fragment>
        )
    }

EDIT: Also, change console.log(clientes) to console.log(cliente) to see individual elements

Upvotes: 1

Related Questions