Reputation: 319
I have a react component that takes an array of objects and maps them into another react component in the view. I am having a hard luck while testing it as it gives this error:
TypeError: data.map is not a function
Here's the test i wrote. Notice i a passing the data prop which i believe should make it work?
content.test.js
import React from 'react';
import { shallow, mount } from 'enzyme';
import { expect } from 'chai';
import Content from '../components/Content.jsx';
describe('<Content />', () => {
const data = {
created: '2017-02-21T09:50:21.441815Z',
duration: 1575,
final_script: 'some script',
language: 'en-GB',
rating: 2,
url: 'some url',
};
it('renders without exploding', () => {
mount(<Content data={ data } />);
});
});
and here's there component itself
content.jsx
function Content(props) {
const { data } = props;
return (
<div className='content_container'>
{
data.map((content, index) => <AudioBox data={ content } key={
index } />)
}
</div>
);
}
Content.propTypes = {
data: React.PropTypes.arrayOf(React.PropTypes.object),
};
export default Content;
and here's the component which calls this Content component
home.jsx
class Home extends Component {
constructor(props) {
super(props);
this.state = {
content: null,
};
this.logout = this.logout.bind(this);
}
componentDidMount() {
const token = localStorage.getItem('i2x_token');
const requestURL = API_CONTENT;
const requestObj = {
method: 'GET',
headers: new Headers({
Authorization: `JWT ${token}`,
}),
};
request(requestURL, requestObj).then((reply) => {
if (reply.results.length > 0) {
this.setState({ content: reply.results });
} else {
console.log('no reply from API');
}
});
}
logout() {
localStorage.removeItem('i2x_token');
browserHistory.push('/');
}
render() {
const data = this.state.content;
return (
<div className='container'>
<Header logout={ this.logout } />
{ data !== null &&
<Content data={ this.state.content } />
}
</div>
);
}
}
export default Home;
What's wrong here?
Upvotes: 2
Views: 14434
Reputation: 104529
I think data
that you are setting is not an array
, because of that you are getting the error.
Check this:
let data = {};
data.map(el => console.log(el))
Make sure that data should be an array, you can put the check also, before using map
by Array.isArray
, like this:
Array.isArray(data) && data.map((content, index) => <AudioBox data={content} key={index} />
Try this:
Define the data in this way:
const data = [
{
created: '2017-02-21T09:50:21.441815Z',
duration: 1575,
final_script: 'some script',
language: 'en-GB',
rating: 2,
url: 'some url',
}
];
Upvotes: 8