Generaldeep Generaldeep - 1 month ago 13
React JSX Question

React, TypeError (this.props.data.map is not a function) on an Array obj

Thank you for stopping by to help. I am working with a react/redux app. One of the component is using a lifecyle method to retrieve data from an API. Once recieved, the data JSON data is held within an array. My initialState for the data coming back is an empty array.

When the component listening to the state change is mounted, the data is rendered on to the page, but then 2 seconds later I am getting a

Uncaught TypeError: jobs.map is not a function


Component making the API call using lifecyle method and listening for state change

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getJobs } from '../../actions';
import { Card, Grid, Image, Feed } from 'semantic-ui-react';
// import './home.css';

const renderJobs = jobs => jobs.map((job, i) => (
<Card.Group stackable key={i}>
<Card className="jobscard">
<Card.Content>
<Card.Header href={job.detailUrl} target="_blank">{job.jobTitle}</Card.Header>
<Card.Meta>{job.location}</Card.Meta>
<Card.Description>{job.company}</Card.Description>
</Card.Content>
</Card>
</Card.Group>
));

class GetJobs extends Component {

componentDidMount() {
this.props.getJobs();
}

render() {
const { jobs } = this.props;
return (
<div className="getjobs">
{renderJobs(jobs)}
</div>
);
}
}

export default connect(({ jobs }) => ({ jobs }), { getJobs })(GetJobs);


Action creator/action

export const getJobsRequest = () => fetch('https://shielded-brushlands-43810.herokuapp.com/jobs',
)
.then(res => res.json());

// action creator
export const getJobs = () => ({
type: 'GET_JOBS',
payload: getJobsRequest(),
});


Reducer

import initialState from './initialState';

export default function (jobs = initialState.jobs, action) {
switch (action.type) {
case 'GET_JOBS_PENDING':
return { ...jobs, isFetching: true };
case 'GET_JOBS_FULFILLED':
return action.payload;
case 'GET_JOBS_REJECTED':
return jobs;
default:
return jobs;
}
}


And intial state

export default {
userData: {},
jobs: [],
}


enter image description here

any thoughts on why this is happening?

Answer Source

You can put a simple check to ensure that your jobs is ready before you attempt rendering it.

{jobs.length && renderJobs(jobs)}