I am fetching data from firebase
and set the data using useState
, but when I am looping through in component return not viewing anything in the loop. Here is my code.
function App() {
const regRef = ref(database, "Tasks/");
const [tasks, setTasks] = useState([{ title: "Task List" }]);
useEffect(() => {
onValue(regRef, (snapshot) => {
snapshot.forEach((childSnapshot) => {
childSnapshot.forEach((task) => {
setTasks((oldTasks) => [...oldTasks, task.val()]);
});
});
});
}, []);
return (
<div className="App">
<div>Rendering data</div>
{tasks.forEach(function (task) {
console.log("rendering value: " task.title);
return (
<>
<h2>{task.title}</h2>
<h4>{task.description}</h4>
</>
);
})}
</div>
);
}
In this view, there is only Rendering data div, but in console log
I am getting all the value
CodePudding user response:
Problem
forEach
just iterate the array it doesn't return anything. That's why you can't see anything. Because it doesn't returning anything
Solve
Try this. Because map
returns an array.
{tasks.map(function (task) {
console.log("rendering value: " task.title);
return (
<>
<h2>{task.title}</h2>
<h4>{task.description}</h4>
</>
);
})}