skip to Main Content

In my App.tsx, I’m using a useState variable waitMessage to store string and a useState variable waitComp to store a component. waitMessage is passed as props to waitComp to show any text message whenever its values is updated. In useEffect, I’m calling an AJAX request, and updating the value of waitMessage, but the same is not updating the message showing in waitComp. The same component is getting updated when not stored as useSate variable. Following is my code:

function App() {
    const dependencies: string[] = [];
    const [waitMessage, setWaitMessage] = useState("Waiting for Server Auth...");
    const wait = <Wait text={waitMessage}/>;
    const [waitComp, setWaitComp] = useState(wait);

    const checkStatus = () => {
        const ajaxSet: AjaxType = {
            callback(request: XMLHttpRequest): void {
                const response = request.response;
                console.info(response); // Getting expected response
                setWaitMessage("Response Received...");
                // Updating waitMessage, but not waitComp
            }, params: {}, url: "http://localhost:8080/user/status"
        };
        callAjax(ajaxSet);
    };

    useEffect(() => {
        checkStatus();
        return () => {
        };
    }, dependencies);


    return <Router>
        <Switch>
            <Route exact path="/">
                {waitComp}
            </Route>
            <Route>
                <PageNotFound/>
            </Route>
        </Switch>
    </Router>;
}

I need to store the component as useState cause I need to change the component under certain conditions. The wait component is getting updated if I directly use it like this:

<Route exact path="/">
    {wait}
</Route>

Can you please explain the cause and solution for this? Thanks!

2

Answers


  1. You can update your waitComp state based on the previous state and the new waitMessage.

    For example:

    setWaitComp(prevState => <Wait text={waitMessage}/>);
    
    Login or Signup to reply.
  2. I don’t see any point of storing <Wait text={waitMessage}/> in a state.
    Instead what you can do is,

    <Route exact path="/">
      <Wait text={waitMessage}/>
    </Route>
    

    Once waitMessage is changed, it will render the component again.

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