Reputation: 49
I want to map data which I've received in Notifications useState hook. But the problem is console showing me the following error
'NotificationsData' is not defined
I'm receiving data in Notifications hook successfully but don't know how to map that data. I've searched about the return statement and cleanup in useEffect but I didn't understand how do I implement that on my case.
useEffect(() => {
const NotificationsData=()=>{
return(
<>
{
Notifications.map((value)=>{
<h1>{value}</h1>
})
}
</>
)
}
}, [Notifications])
return (
<>
<Header />
<Container fluid>
<Row>
<Col className="my_body">
<br />
<br />
<NotificationsData />
</Col>
</Row>
</Container>
<Footer />
</>
)
Upvotes: 0
Views: 56
Reputation: 63524
NotificationsData
isn't recognised as a component because you've included it within the scope of the useEffect
method. Move it outside instead and pass in the data from your state as props.
// Get a hook function
const {useState, useEffect} = React;
const data = ['one', 'two', 'three', 'four'];
// Mock API function to return some data
function getData() {
return new Promise((res, rej) => {
setTimeout(() => res(data), 1000);
});
}
// Your component. Pass in the notification data as props.
function NotificationsData({ data }) {
return data.map(el => <h1>{el}</h1>);
}
function Example() {
const [notifications, setNotifications] = useState([]);
// Fetching some data and setting the state
useEffect(() => {
getData().then(data => setNotifications(data));
}, []);
// If there's nothing in state return a div or spinner
if (!notifications.length) return <div>Loading</div>;
// Otherwise return your component passing in the state
return <NotificationsData data={notifications} />;
};
// Render it
ReactDOM.render(
<Example />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Upvotes: 1
Reputation: 537
You wont be able to access NotificationData coz it is encapsulated inside useEffect,Try defining it outside useEffect that would work.
Upvotes: 0
Reputation: 75
React component don't know what is NotificationsData because you declare it inside the useEffect scope.
create a new component called NotificationsData and then import it and render it in the Parent component (current one).
it should work.
Upvotes: 1