1

Here i want to render the AlertSound component when value of bitcoin state changes but it only render when i refresh application and not when value of state is changed. value of bitcoin state is getting update but the AlertSound component renders only once when app is reloaded

App.js:-

const App = () => {
  const [bitcoin, setBitcoin] = useState();

  const myRef = useRef("");

  const fetchDetail = async () => {
    const { data } = await Axios.get(
      "https://api.coincap.io/v2/assets/bitcoin"
    );
    setBitcoin(Math.floor(data.data.priceUsd));
  };

  useEffect(() => {
    const interval = setInterval(() => {
      fetchDetail();
    }, 1000);
    return () => clearInterval(interval);
  }, []);

  return (
    <div>
      <h1>{bitcoin}</h1>
      {bitcoin < 41405 ? <AlertSound /> : " "}
    </div>
  );
};
export default App;



AlertSound.js:- 

const AlertSound = () => {
  const myRef = useRef(null);
  return (
    <div>
      <audio ref={myRef} src={SoundFile} autoPlay />
    </div>
  );
};

1 Answers1

1

Add dependency of bitcoin state in useEffect

const App = () =>{

const [bitcoin, setBitcoin] = useState();

const myRef = useRef("");

const fetchDetail = async () =>{
const {data} = await Axios.get("https://api.coincap.io/v2/assets/bitcoin");
setBitcoin(Math.floor(data.data.priceUsd));
}

useEffect(() => {
const interval = setInterval(() => {
fetchDetail();
}, 1000);
return () => clearInterval(interval);
}, [bitcoin]);

return(
<div>
<h1>{bitcoin}</h1>
{bitcoin < 41405 ? <AlertSound/> : " "}
</div>
)
}
export default App;
Harsh Mangalam
  • 1,116
  • 1
  • 10
  • 19
  • bitcoint state is getting update {bitcoin < 41405 ? : " "} AlertSound component only runs when app is reloaded it should render when bitcoin price drops the specified value – Naveen sharma Aug 02 '21 at 05:25