I'm very new in React Native. I'm stuck since 2 days. I tried to look for solution.I'm trying to fetch a plannings array from a database which as the following shape:
export interface Plannings { [day: string]: { session: string; when: string; time: string }[];}
When I fetch data for the first time I get the data but when I reload I get undefined is not an object (evaluating 'userPlanning[day]')
const fetchPlannings = useCallback(async () => { const planningsData = await AsyncStorage.getItem('plannings'); try { if (planningsData) { const planningStored = await JSON.parse(planningsData); setPlannings(planningStored); const nextSessionData = getNextSession(planningStored, user, frenchDay()); setNextSession({ session: nextSessionData.session, time: nextSessionData.time, when: nextSessionData.when }) } } catch (e) { console.log(e) } }, []); useEffect(() => { fetchPlannings(); }, []);
And here is the getNextSession method:
const getNextSession = (plannings: Plannings[], user: User, day: string): Session => { const userPlanning = plannings[user.group - 1]; const hours = new Date().getHours(); console.log(day); if (hours >= 4 && hours <= 11) { return userPlanning[day][0]; } else if (hours >= 12 && hours <= 20) { return userPlanning[day][1]; } else { return userPlanning[day][0]; } }
Thanks for helping me =)