Naveen sharma
Naveen sharma

Reputation: 45

how to trigger conditional rendering when a state value is changes right now conditional rendering is working only when application is loaded

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>
  );
};

Upvotes: 1

Views: 64

Answers (1)

Harsh Mangalam
Harsh Mangalam

Reputation: 1299

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;

Upvotes: 1

Related Questions