Home > front end >  Log one field from each element of an array
Log one field from each element of an array

Time:11-18

I have objects, in the database. I want to grab the userId using axios, but when I tried to console.log() it. It shows undefined. hen I hardcoded it and targeted it by array, it shows.

How can I console log all of userId? I would like to grab it so I can use it as an endpoint for my database

const res = await userRequest.get('user/find/' userId)

I want to grab the userId only.

import React, { useEffect, useState } from 'react'
import { format } from 'timeago.js'
import { userRequest } from '../../requestMethod'
import './Widgetlg.css'
const WidgetLg = () => {
  const Button = ({ type }) => {
    return <button className={'widgetLgButton '   type}>{type}</button>
  }
  const [orders, setOrders] = useState([])
  const [users, setUsers] = useState([])

  useEffect(() => {
    const getOrders = async () => {
      //this is just a shorcut api
      try {
        const res = await userRequest.get('orders')
        setOrders(res.data)
        console.log(res.data?.userId)
        console.log(res.data)
        console.log(res.data[0].userId)
      } catch (error) {
        console.log(error)
      }
    }
    getOrders()
  }, [])

  useEffect(() => {
    const getUsername = async () => {
      try {
        const res = await userRequest.get('user/find/')
        setUsers(res.data)
      } catch (error) {}
    }
    getUsername()
  }, [])

  return (
    <div className="widgetLg">
      <h3 className="widgetLgTitle">Latest Transactions</h3>
      <table className="widgetTable">
        <tr className="widgetLgTr">
          <th className="widgetLgTh">Customer</th>
          <th className="widgetLgTh">Date</th>
          <th className="widgetLgTh">Amount</th>
          <th className="widgetLgTh">Status</th>
        </tr>
        {orders.map((order) => (
          <tr className="widgetLgTr">
            <td className="widgetLgUser">
              <span className="WidgetLgName"> **I want here to show the username** </span>
            </td>
            <td className="widgetLgDate"> {format(order.createdAt)} </td>
            <td className="widgetLgAmmount">P {order.amount} </td>
            <td className="widgetLgStatus">
              <Button type={order.status} />
            </td>
          </tr>
        ))}
      </table>
    </div>
  )
}

export default WidgetLg

CodePudding user response:

You could try something like this if I understand you correctly

const userIdsArray = res.data.map(d => d.userId);
console.log(userIdsArray);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

res.data is an array. To log all elements, you could just iterate over them:

res.data.forEach(el => console.log(el.userId));

The reason that console.log(res.data) gives undefined is that the array itself doesn't have a userId field, only the elements of the array do.

  • Related