skip to Main Content

I have a component that holds a single boolean in state and renders a button that toggles that value.
The value of the boolean comes from an object that is created in a parent component. When the object is created the button is displayed but the actual value of the boolean is set slightly later by another process.

Edit broken-shape-wrnkhn

const Child = ({obj})=>{
  const [bool, setBool] = useState(obj.aBool);

  useEffect(()=>{
    obj.aBool = bool;
    console.log(obj);
  }, [bool]);

  const toggle = ()=>{
    setBool(!bool);
  }

  return <button onClick={toggle}>Value is {bool!=undefined?bool.toString():'...'}</button>
}

The button renders while the boolean is undefined and the view reflects this. The boolean is then set later by a setTimeout which you can see if you open the console.
But the value does not reflect in the button until you click, after which is works fine.

Is there a way to watch the object property so that when it updates after 2 seconds the button re-renders to reflect the change?

2

Answers


  1. I wonder if you’re looking to maybe use Suspense which has a fallback until something has finished loading.

    I threw a small example together in codepen, I hope it help.

    https://codepen.io/huzi8t9/pen/GRzEqpX

    import React, { useState, lazy } from "https://esm.sh/react";
    import ReactDOM from "https://esm.sh/react-dom";
    
    const SuspensfulComponent = lazy(() => {
      
      return new Promise(function(resolve) {
            setTimeout(() => {
              resolve({ default: () => <p>Loaded </p> })
            }, 5000);
        })
    });
    
    const App = () => {
      return (
        <React.Suspense fallback={<p>Wait...</p>}>
          <SuspensfulComponent />
        </React.Suspense>
      );
    };
    
    const root = ReactDOM.createRoot(document.getElementById("app"));
    
    root.render(<App />);
    

    The above example will show "Wait…" until the promise is resolved in the SuspensefulComponent — the component will return some basic text but, if you had genuine data loading inside your component, Suspense would fire and fallback when loading is happening.

    Hope this helps.

    Login or Signup to reply.
  2. Shouldn’t need to duplicate the state in the Child. It outta just rerender when the parent changes.

    Not sure if this is what you were looking for. Hope it helps!

    https://codesandbox.io/s/epic-chaplygin-46d38q?fontsize=14&hidenavigation=1&theme=dark&file=/src/App.js:0-45

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search