I am using a store in react using Zustand where I create a timer that updates the time every second using a setInterval()
function.
I created it in a store in hopes to pass the time to various children components while keeping the time stored and shared from a central location.
I am able to update time in the store and log it successfully but when I pass it to the child components they are not updating the time. How can I pass the updated time and cause a re-render of the time every second it's passed? I do not want to use a useEffect()
in the child components.
ZUSTAND STORE
import create from "zustand";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
dayjs.extend(utc);
import toObject from "dayjs/plugin/toObject";
dayjs.extend(toObject);
import timezone from "dayjs/plugin/timezone";
dayjs.extend(timezone);
import { IGlobalStyles} from "utils/types";
import { useEffect } from "react";
interface IStyles {
time?: any;
}
const timer = setInterval(function () {
const time = dayjs().format("hh:mm:ss A")
console.log("Time in store", time);
return(time)
}, 1000);
const useGlobalStyles = create<IStyles>((set) => ({
time: timer
})
);
export default useGlobalStyles;
CHILD COMPONENT(This is where I want to display the time)
import React from "react";
import {
StyleSheet,
TouchableOpacity,
Text,
Button,
View,
Dimensions,
} from "react-native";
import {
NavigationRouteContext,
useNavigation,
} from "@react-navigation/native";
import * as Shadows from "../../styles/shadows";
import useGlobalStyles from "stores/GlobalStyles";
interface IDateTime {}
export default function DateAndTime({}: IDateTime) {
//Access zustand store and retreive the current updated time
const time = useGlobalStyles((store) => store.time);
return (
<View style={[styles.container(window.width), styles.shadow]}>
{/*I want this text component to update time from react Zustand Store*/}
<Text>{time}</Text>
</View>
);
}
const styles = StyleSheet.create({
container: (containerWidth: any) => ({
borderWidth: 1,
position: "absolute",
top: 30,
right: 25,
backgroundColor: "#FFFFFF",
justifyContent: "center",
//marginBottom: "5%",
// width: 422,
// height: 128,
width: containerWidth * 0.45,
height: "8%",
borderRadius: 10,
padding: 20,
}),
text: {
alignSelf: "flex-end",
alignItems: "center",
fontSize: 10,
color: "black",
fontWeight: "700",
height: 20,
textAlign: "center",
},
shadow: { ...Shadows.componentShadow },
});