0

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

2
  • Do you want to loop through the items present in the response? Looping though the object itself doesn't seem very logical. Commented Nov 26, 2020 at 22:53
  • Try using {data.key} instead of {key} Commented Nov 27, 2020 at 6:09

3 Answers 3

2

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

2 Comments

That is very true and an excellent point, but doesn't address the basic problem that an undeclared variable, key, is being used.
Thanks. was able to fix it
0

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.

Comments

0

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;

2 Comments

HI, it worked but when i wanted to render or loop through "items" which is an array of objects withing the json response, i get errorCannot read property '2' of undefined
For items or any array present inside the object, you can create a new state for items like this and fetch it (changed the code):

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.