0

I encountered an issue when I used map function in React to iterate data because the data is object. So I tried to use _.map function of Lodash to convert from object to array. Then I want to iterate the data using mapfunction.

It didn't work as I had expected and I'm wondering what is the problem.

Should it be working? It is a ok to use _.map to iterate in React?

The data structure enter image description here

The code

import React, { Component } from 'react';
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { addData } from "../actions/index";
import _ from "lodash";

class List extends Component{
    componentDidMount(){
        this.props.addData()
    }
    render(){
        let item;
        if(this.props.data) {
          item = _.map(this.props.data, data => {

         return (
             <li key={data.id}>
             {data.title}
             </li>
         /* this returns empty data. Only bullet button appears.
         In console, it says [Each child in an array or iterator should have a unique "key" prop.]
         Even though I added a key value. */
         )
     })
    }   


return(
    <div>{item}</div>
)
}
}

function mapStateToProps(state){
    return {
    data : state.data
}
}

export default connect(mapStateToProps, {addData})(Search);

UPDATE:

To debug, did a console.log(this.props.data), which produced this output:

Object { data: Array[100] }
9
  • Are you getting the data from an API? Commented Nov 14, 2017 at 17:02
  • yes. using Fetch in Redux. api address is this one jsonplaceholder.typicode.com/posts. Commented Nov 14, 2017 at 17:04
  • 1
    Are you waiting for the API call to finish before rendering the component? Commented Nov 14, 2017 at 17:05
  • I use redux thunk to get data asynchronously. Commented Nov 14, 2017 at 17:08
  • "I encountered an issue when I used map function in React to iterate data because the data is object". The data structure you posted is an array. Commented Nov 14, 2017 at 17:19

1 Answer 1

1

Based on your console.log(this.props.data) output, we can see that value assigned to this.props.data is:

{ data : [ /* fetched objects... */ ] }

That array you're trying to call map on is a level deeper than you expected, so indeed it looks like you're not correctly selecting the fetched and stored data in your mapStateToProps.

Try this instead:

function mapStateToProps(state){
  return {
    data : state.data.data
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

You are right and it worked! Thank you so much. when I have a similar problem from next time, I will try this way.

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.