0

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

2
  • You should be using the useState hook for your suppliers_list. Declaring it as a var means it is not reactive so your component will ignore changes to it. Commented Jan 27, 2020 at 22:56
  • @ChaseDeAnda I am new to Reactjs please can you answer it? i tried to use useState but i got error Objects are not valid as a React child Commented Jan 27, 2020 at 23:03

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.