'React response data is undefined when rendered
In my react app I am fetching data from API, the response object is as below:-
posts {
total: 3,
data:[
{some data},
{some data},
{some data}
] }
The data is rendered using a map() function.
but whenever the page renders the data is displayed only once. After the first render when the page is re-rendered the data array is undefined (in console.log).
code for component:-
const function = () => {
const dispatch = useDispatch();
const { posts, isSuccess } = useSelector((state) => state.posts);
useEffect(() => {
dispatch(getPosts());
}, [dispatch]);
return (
<>
<div className="main-content">
{posts.data.map((post) => (
<Post
postId={post._id}
postSubject={post.subject}
/>
))}
</div>
</>
);
}
export default function;
Solution 1:[1]
You can try this before map function.
<React.Fragment>
{typeof object.data === typeof [] && (
<React.Fragment>
{object.data.map((obj, index) => {
return <React.Fragment>return some code .....</React.Fragment>;
})}
</React.Fragment>
)}
</React.Fragment>
I hope it's work
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Matee Suttapak |
