简体   繁体   中英

Setting the initial value of a useState hook before useState is executed

So I'm trying to load some data from local storage for a Chrome extension. I need to use this data to set the initial value of a useState hook. Here's what I tried so far:

const Popup = (): ReactElement => {
    // load state from local storage
    let overviewIsOpenLS;
    useLayoutEffect(() => {
        chrome.runtime.sendMessage({ getFromLocalStorage: 'overviewIsOpen' }, response => {
            overviewIsOpenLS = response;
        });
    }, []);

    console.log(overviewIsOpenLS); // returns undefined

    // trying to use the value of overviewIsOpenLS as the initial value of this useState
    const [overviewIsOpen, setOverviewIsOpen] = useState<boolean>(overviewIsOpenLS);

    return <>...
}

I double/triple checked the value in local storage, it is correct. However, the useEffect at the top doesn't work at this point and the variable remains undefined. Any idea how this can be achieved?

I'd make the asynchronous request in the parent component, then conditionally render the child (the Popup ) only once the request finishes:

// parent component
const [overviewIsOpenLS, setOverviewIsOpenLS] = useState();
useLayoutEffect(() => {
    chrome.runtime.sendMessage({ getFromLocalStorage: 'overviewIsOpen' }, setOverviewIsOpenLS);
}, []);
return overviewIsOpenLS === undefined ? null : <Popup overviewIsOpenLS={overviewIsOpenLS} />;
// then in Popup:
const [overviewIsOpen, setOverviewIsOpen] = useState<boolean>(props.overviewIsOpenLS);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM