简体   繁体   中英

Looping through an object in react

Learning react

Trying to loop through an object from an API call that returns a json object and display it but struggling to implement it

This is the component that should render it

    export default class ProfilePage extends Component {
  constructor() {
    super();
    this.state = { data: '' };
  }

  mapObject(object, callback) {
    return Object.keys(object).map(function (key) {
        return callback(key, object[key]);
      })

  }

  async componentDidMount() {
    const response = await fetch(`https://indapi.kumba.io/webdev/assignment`);
    const json = await response.json();
    // console.log(json)
    this.setState({ data: json });
    
  }

  

  render() {
    const data = this.state.data
    console.log(data)
    return (
      <div className="row">
          {Object.values(data).map(data => {
              <div key={key}>
                {data[key]}
              </div>
          })

          }
         Woerkkk please
    </div>
    
    );
  }
}

All I'm getting is a blank screen.

in the console i get the error 'key' is not defined no-undef

You are missing a return statement in your map for your render method. Edit: Key is not returned from Object.values

Either reconfigure with a return statement like so:

{Object.keys(data).map(key => {
          return (<div key={key}>
            {data[key]}
          </div>);
      })

Or alternatively you can implicitly return from arrow function using brackets

{Object.keys(data).map(key => (
          <div key={key}>
            {data[key]}
          </div>)
      ))

Using Object.values(myObj) you can get all object values as a array. So, with this array, you can iterate over the array and show your items, like this:

{Object.values(myObj).map(value => <p>{value}</p>)}

Don't forget use key prop when iterating.

You can use useState and useEffect to fetch the object data

 const App = () => { const [objData, setObjData] = useState({}); const [objItems, setObjItems] = useState([]); const fetchObj = async () => { const response = await fetch(`https://indapi.kumba.io/webdev/assignment`); const data = await response.json(); setObjData(data); setObjItems(data.items); } useEffect(() => { fetchObj() },[]); return( <div> <h1> Order Id:{objData.order_id}</h1> // or any other objData keys <h1>Items: </h1> <ul> { objItems.map((i, idx) => { return( <li key={idx}>Name: {i.name}, Category: {i.category}, Price: {i.price}, Currency: {i.currency}</li> ) }) } </ul> </div> ) } export default App;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM