@pikapikamart
Posted
This is the code in there.
const date = new Date(user.created_at)
const dateJoined = date.getDate()
const year = date.getFullYear()
const month = months[date.getMonth()]
console.log(year)
console.log(month)
console.log(dateJoined)
Basically, you are getting undefined
and NaN
is because you are accessing the user.created_at
from the useState
value and since the useEffect
that holds the setState
hasn't fired yet, the data will not be stored immediately. That is why at first run, you will get those results of undefined
and NaN
So the best answer to prevent this is that, have a separate component that holds the whole card. One is your Main
component, the other one is Card
component.
Then on your Main
component, you set all the datas in there, then only use:
const Main = props =>{
const [ user, setUser ] = useState({});
.....
insert useEffect to fetch data, convert it to async/await
........
.....
if ( user ) { # only run this when user has the required Datas
return <Card user={user} />
}
}
This way, the Card
component will only run if the user has loaded. The Card
component will all have the data usage and you won't get any falsy values.
Marked as helpful
@pikamart, 🤣🤣. The condition is what I was missing. Thank you
@pikapikamart
Posted
@ChamuMutezva Oh hahaha I was just about to suggest using context since I only thought there was only 1 fetch being made, I forgot that there is a searchbar hahaha
Well awesome if you made it work!