Inject prop value periodically

Viewed 19

I've got a simple problem I can't solve. I would like to periodically inject prop value, and when the value is injected, re-render the element in real-time.

The simplest example for reproduction - I have a badge with a prop, where I try to periodically put a number with setInterval and a reference. However, it doesn't do anything:

index.js

import * as React from "react";
import ReactDOM from "react-dom/client";
import IconWithBadge from "./Icon";

var x;
setInterval(() => {
  x = Math.ceil(Math.random() * 10);
  console.log("changing to " + x);
}, 3000);

ReactDOM.createRoot(document.querySelector("#root")).render(
  <IconWithBadge badgeCount={x} />
);

Icon.js

import * as React from "react";
import Badge from "@mui/material/Badge";
import MailIcon from "@mui/icons-material/Mail";

export default function SimpleBadge({ badgeCount }) {
  return (
    <Badge badgeContent={badgeCount} color="primary">
      <MailIcon color="action" />
    </Badge>
  );
}

you can also find it at codesandbox right here: https://codesandbox.io/s/simplebadge-material-demo-forked-k4okdi?file=/index.js

Any help highly appreciated.

1 Answers

This solves the issue : The problem in the previous code was , our page was not getting re-render when value of x was changing .

Simple solution to this problem is to render the root when value of x changes i.e inside setInterval

import * as React from "react";
import ReactDOM from "react-dom/client";
import IconWithBadge from "./Icon";
let root = ReactDOM.createRoot(
  document.getElementById('root')
);

var x ;
root.render(<IconWithBadge badgeCount={x} />);

setInterval(() => {
  x = Math.ceil(Math.random() * 10);
  console.log("changing x to " + x);
  root.render(<IconWithBadge badgeCount={x} />)
}, 3000);


Link for the sandbox

Related