Reputation: 90
I am trying to use useState however it the setters do not seem to be working. Code has been removed for simplicity. As it stand the code does run however the initial set state is always undefined. This is the case for setTasks and setCurrentUserId. I am unsure why this is the case. I understand that useState is async(?) so this could impact when the code is rendered. But even so as I understand atleast setCurrentUserId should be set. Yet if is set
const [userId, setUserId] = useState(sub || 'anon')
to const [userId, setUserId] = useState('')
then it never gets set to the value from the useEffect.
I am also unsure how if I could, what to set the use Effect listener? to. If it set it to watch for tasks update then it gets stuck in a perpetual loop. I am unsure were to go from here.
const individualJournal = () => {
// State
const sub = useAuthStore((state) => state.sub)
const [userId, setUserId] = useState(sub || 'anon')
const [tasks, setTasks] = useState<any>(null)
const [taskId, setTaskId] = useState<any>()
const [currentUserId, setCurrentUserId] = useState<string>(sub || 'anon')
const [postsExists, setPostsExists] = useState(false)
// Post related
const getFormikDefaultValues = async (): void => {
// Sets all the formik default values to pre populate fields
// Will be run on rerender
const newDefaultUsername = sub || 'anon'
setCurrentUserId(newDefaultUsername)
}
const getPosts = async (): Promise<void> => {
const posts: any = await database
.get('posts')
.query(Q.where('user_id', userId))
.fetchCount()
setPostsExists(false)
if (posts > 0) {
setPostsExists(true)
}
}
useEffect(() => {
async function setTasksFunc(): Promise<void> {
const getTasks: any = await database
.get('tasks')
.query(
Q.where('is_completed', true),
Q.where('user_id', userId)
)
console.log(getTasks)
setTasks(getTasks)
console.log(tasks)
}
setTasksFunc()
getPosts()
setCurrentUserId(sub || 'anon')
}, [])
return (
<TamaguiProvider config={config}>...</TamaguiProvider>
)
}
export default individualJournal
Thanks for the help.
Upvotes: 0
Views: 41