Search code examples
reactjstypescript

make the live visitor counter change without refresh


My client want to make total visitor counter.

Is it possible to make the total visitor counter increase but when the user not refresh the page? so the users can see the total visitor increasing without refresh the page. What should i add to make it happen? Please kindly explain in detail because i am new to typescript.

here's my code

type visitortype={
  count: number;
}


const Footer = () => {
  const [visitor, setvisitor] = useState<visitortype>();

  useEffect(() => {
    fetch('https://count.cab/hit/ghG6Oirn0b')
    .then(response => response.json())
    .then(allvisitor=>  setvisitor(allvisitor))
    .catch(error => console.log(error));
  }, []);

 return (
    <GridItem
      w="100%"
      h={{ base: "80px", lg: "300px" }}
      colSpan={{ base: 8, lg: 4 }}
    >
      <VStack
        align={{ base: "center", lg: "stretch" }}
        marginTop={{ base: "0", lg: "60px" }}
        marginLeft={{ base: "0", lg: "50px" }}
      >
        <Box w={{ base: "100px", lg: "220px" }} paddingBottom={"10px"}>
          <Image src={imgLogoMd} alt="Logo" w="100%" />
          <HStack>
            <Text fontSize={{ base: "xs", lg: "md" }} textAlign={"justify"}>
              {visitor?.count} Visitor
            </Text>
          </HStack>
        </Box>
      </VStack>
    </GridItem>
  );

};

Solution

  • You can look into Web Sockets:

    https://developer.mozilla.org/en-US/docs/Web/API/WebSocket

    You can also look into applying a setInterval perhaps to "poll" for changes.

    Found this: How to setInterval for every 5 second render with React hook useEffect in React Native app?

    Note the clear interval part.