Reputation: 109
I am using the react hooks but in that useEffect is not working. As in the console start and end are not printing. Also I am using react in rails project.
import PropTypes from 'prop-types';
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
const DetailInterview = () => {
const [participants, setparticipants] = useState([])
const [interviews, setinterviews] = useState([])
async function fetchParticipantsList() {
fetch('/api/v1/participants').
then((response) => response.json()).
then((participants) => setparticipants({ participants }));
};
async function fetchInterviewsList() {
const { match: { params: { id } } } = this.props;
fetch(`/api/v1/interviews/${id}`).
then((response) => response.json()).
then((interviews) => setinterviews({ interviews }));
console.log("sa",interviews)
};
useEffect(() => {
console.log('start')
fetchParticipantsList();
fetchInterviewsList();
console.log('end')
});
const interviewslist = JSON.stringify(interviews)
console.log('interviewlist: ',interviewslist)
return (
<div>
<h3>All participants</h3>
<table>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Description</th>
<th>Is Published</th>
</tr>
</thead>
<tbody>
{
interviewslist.map((interview) => {
return (
<tr key={interview.id}>
<td>{interview.id}</td>
<td>{interview.interview_id}</td>
<td>
{/* <Link to={`/posts/${post.id}`}> */}
{interview.participant_id}
{/* </Link> */}
</td>
<td>{interview.created_at}</td>
<td>'Yes No'</td>
</tr>
)
})
}
</tbody>
</table>
</div>
);
}
export default DetailInterview;
Can anybody please help me why this is not working. Because of which I think it is showing this error:
Uncaught TypeError: interviewslist.map is not a function.
Also this console is printing twice: console.log('interviewlist: ',interviewslist)
Upvotes: 1
Views: 328
Reputation: 5854
You should use interviews not interviewList. You actually stringify interviews to interviewList. So interviewList is basically a string not an array. So Please use interviews.map
{
interviews? interviews.map((interview) => {
return (
<tr key={interview.id}>
<td>{interview.id}</td>
<td>{interview.interview_id}</td>
<td>
{/* <Link to={`/posts/${post.id}`}> */}
{interview.participant_id}
{/* </Link> */}
</td>
<td>{interview.created_at}</td>
<td>'Yes No'</td>
</tr>
)
}) : null
}
Upvotes: 1
Reputation: 144
You are trying map a string, JSON.stringify converts a JavaScript object or value to a JSON string.
Try use JSON.parse in this case.
Upvotes: 1