Function does not work when I go to the page back, and then return to the page (React)

Viewed 42
function Final_Set(){
  return(
    <div id="exercise_sets_decider_box">
    {
      (function(){
        console.log(1);
        Final_set_page();
      })()
    }
   </div>
   );

function App(){
 const [mode, Setmode] = useState("0");
 if (mode === "0"){
  $(document).on('click', "#purple_box_1", function(e){
 Setmode("Final");
});
  return(
 <div id="purple_box_1">
 </div>
);
} else if(mode==="Final"){
  $(document).on('click', "#purple_box_2", function(e){
  Setmode("0");
});
  return(
<div>
 <Final_Set></Final_Set>
<div id="practice"></div>
 <div id="purple_box_2">
 </div>
</div>
)
}
}

In brief, Final_set_page function is appending html code in div:#practice, like $("#practice").append('blahblah'). If I go from mode '0' to mode 'Final', Final_set_page() is well working. But if I return to mode '0' and go back to mode 'Final', console.log() is well working but Final_set_page() is not working. I don't know the reason, and I can't find the solution. Please help!

1 Answers

Maybe the problem is in jQuery.

I have rewritten the code. Maybe edit this code instead according to your needs. By the way, we have no idea what Final_set_page is...

function Final_Set() {
 useEffect(() => {
  console.log(1);
  Final_set_page(); // I don't know what it is, so leaving it here. Move it if it is a component.
 }, []); // [] empty dependency array means useEffect only runs once.

 return (
  <div id="exercise_sets_decider_box">
   exercise_sets_decider_box
  </div>
 );
}

function App() {
 const [mode, setMode] = useState("0"); // SetMode does not follow the convention for naming variables.

 const handlePurpleBox1Click = () => setMode("Final"); // I moved this to separate functions so it is easier for you to edit them further.
 const handlePurpleBox2Click = () => setMode("0");

 if (mode === "0") {
  return (
   <div id="purple_box_1" onClick={handlePurpleBox1Click}>
    purple_box_1
   </div>
  );
 }

 if (mode === "Final") { // if the previous return worked, this code is not reachable. This looks cleaner to me.
  return (
   <div>
    <Final_Set></Final_Set>
    <div id="practice"></div>
    <div id="purple_box_2" onClick={handlePurpleBox2Click}>
     purple_box_2
    </div>
   </div>
  )
 }

 return <></> // add this, so the component returns something just in case.
}
Related