skip to Main Content

I am trying to retrieve some data from a CSV that I have stored in a javascript object. I put the array in a react state but I can not target the values from a single object.For example, I would like to retrieve the name value of the object stored inside the array but I keep getting an undefined message when I try to console log it.
here is the code :

  1. Here is the result that I get from papaparse when I do a console.log(result.data) :
(3) [{…}, {…}, {…}]
0: {name: 'item1', quantity: '15', price: '20'}
1: {name: 'item2', quantity: '14', price: '30'}
2: {name: 'item3', quantity: '80', price: '10'}
length: 3
[[Prototype]]: Array(0)
  1. this is the function that retrieve the data from the CSV and pass it in a useState so I can then pass it in html format :
const [dataArray, setData] = useState([]);

const handleFile = (event) => {
        Papa.parse(event.target.files[0], {
            header: true,
            skipEmptyLines: true,
            encoding: "ISO-8859-1",
            complete: function(result) {
               
            const dataArray = [];

               
                const itemObj = {
                    name: "",
                    quantity: "",
                    price: ""
                };

                for (let i=0; i < result.data.length; i++)
                {
                let obj_name = result.data[i].name;
                let obj_quantity = result.data[i].quantity;
                let obj_price = result.data[i].price;  
                Object.assign(itemObj, { name: obj_name });
                Object.assign(itemObj, { quantity: obj_quantity });
                Object.assign(itemObj, { price: obj_price });
                dataArray.push(itemObj);
                }

            )

            setData(dataArray)

            }
        })

    }

and this is the code that I have in the return function in order to display the data in the html but I keep getting errors, I don’t know how to loop over the data in order to display the infos in the html :

            <tbody>
                {dataArray.map((v, i) => (
                    <tr>
                        <th key={i}>{v}</th>                        
                    </tr>
                ))}
                {/* {dataArray.map((v,i) => {
                    console.log(dataArray)
                })} */}
            </tbody>

2

Answers


  1. try to use:

    setData([...dataArray, dataArray])
    
    Login or Signup to reply.
  2. Try using the spread operator:

    setData((prevState) => [...prevState, ...dataArray]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search