Ali
Ali

Reputation: 1759

How to iterate through data and display them in JSX in ReactJS?

I have a function that makes a call to the server and retrieves data in a form of array of json objects, what i want is to iterate through the data and display them in the JSX .

Thw Problem is No thing is being displayed on the screen, not even getting an error. and when I console.log the response i got this:

enter image description here

below is the component

import React from 'react';
import axios from 'axios';

function Supplier(){

    let suppliers_list=[];

    React.useEffect(() => {
        getAllSuppliers();
    });


    const getAllSuppliers = () =>{
        return axios.get('http://localhost:4000/supplier',supplierData).then(
            response=>{
                let allSuppliers = response.data;

                allSuppliers.forEach(element => {
                    suppliers_list.push(
                    <li>{element.supplier_name}</li>
                    );
                });

            },error =>{
                //handle error
            }
        );
    }


    return(
        <div>
            <ul>
                {suppliers_list}
            </ul>
        </div>
    )
}
export default Supplier;

and when I console.log the suppliers_list I got this:

enter image description here

Upvotes: 0

Views: 47

Answers (1)

Gangadhar Gandi
Gangadhar Gandi

Reputation: 2252

Change your code like below,

import React from 'react';
import axios from 'axios';

function Supplier(){

    const [suppliersList, setSuppliersList] = React.useState([]);

    React.useEffect(() => {
        getAllSuppliers();
    }, []); // Hoping you want to execute getAllSuppliers function only once, so [] empty square braces 


    const getAllSuppliers = () =>{
        return axios.get('http://localhost:4000/supplier', supplierData).then(
            response=>{
                setSuppliersList(response.data);
            },error =>{
                //handle error
            }
        );
    }


    return(
        <div>
            <ul>
                {suppliersList.map(supplierObject => {
                return <li>{supplierObject.supplier_name}</li>
                })}
            </ul>
        </div>
    )
}
export default Supplier;

Upvotes: 2

Related Questions