I'm having this problem with React where I'm trying to render a select dropdown with dates stored in my database. The data is fetched succesfully and the states are updated as well, it can be console logged. However the select dropdown is not being rendered as it should:
function Home(){
const [userdata, setUserdata] = useState();
const [historyLogs, setHistoryLogs] = useState();
useEffect(() => {
async function firstRun(){
var userdata = await (await fetch("/me")).json();
var historyLogs = []
firebase.database().ref(userdata.id).once("value", function(snapshot){
snapshot.forEach(child => {
historyLogs.push(child.key);
})});
setHistoryLogs(historyLogs);
setUserdata(userdata);
}
firstRun();
}, [])
function aver(){
console.log(historyLogs);
}
if(!userdata || !historyLogs){
return null
}
else{
return (
<React.Fragment>
<button onClick={aver}>aver</button>
<header>
<img src={logo} height="50px" alt="logo"/>
<select id="cars" name="carlist" form="carform">
<option value="volvo" selected>volvo</option>
{
historyLogs.map(log => {
return <option>{log}</option>
})
}
</select>
<div className="user-info">
<img src={userdata.img} height="50px" style={{borderRadius:"50%"}} alt="user img"/>
<p>{userdata.name}</p>
</div>
</header>
<Toptracks userdata={userdata}/>
</React.Fragment>
)
}
}
export default Home;
With the code I have, the dropdown renders without rendering the historyLogs list, so it only shows this:
and this should be displayed inside (console logged):
(2) ["2021-7-25", "2022-7-25"]
I interesently found out that if I make any change in the code with my local server running, it gets updated as it should be on the first place:
Any help is very much appreciated :)
The solution has been thanks to @click2install and @NickServe on Reactiflux Discord server:
Your once code is in an asyncronous event listener, which means it's running after you set your state to [ ]. You should call setHistoryLogs inside of once instead.
Final solution:
useEffect(() => {
async function firstRun(){
var userdata = await (await fetch("/me")).json();
firebase.database().ref(userdata.id).once("value",
function(snapshot){
var historyLogs = []
snapshot.forEach(child => {
historyLogs.push(child.key)
});
setHistoryLogs(historyLogs);
}
);
setUserdata(userdata);
}
firstRun();
}, [])