Search code examples
javascriptreactjsreact-hookslocal-storagetinymce

How can I set a localStorage variable to match the page that it belongs to?


I have the following component that is used in an online science lab.

I am using localStorage just in case the researcher navigates away from the page and then tries to go back. I want the fossilText to stay there in the text editor.

The problem is, there are multiple instances of the editor because they can work on multiple entries and once and also there are many researchers using the app at the same time.

So my localStorage data gets all mixed up and ends up not matching with the correct page.

Is there a way to set localStorage so that it knows what instance it belongs to?

I tried setting the localStorage.setItem('fossilId', fossilId) but that also gets messed up.

Here is my code:

 const App = (props) => {
    const [fossilText, setFossilTextState] = useState(props.fossilText || "Fossil Text...");
    const [fossilId, setFossilIdState] = useState(props.fossilId);
    var rteContent = '';


    if (localStorage.getItem('fossilState')) {
        rteContent = localStorage.getItem('fossilState');
    } else {
        rteContent = fossilText;
    }

    const [fossilState, setFossilState] = useState(rteContent);

    useEffect(() => {
        localStorage.setItem('fossilState', fossilState)
    }, [fossilState]);



    const updateFossilText = (content) => {
        const request = axios.put(`/api/scienceFossil/${fossilId}/fossilText`, JSON.stringify(content), {
            headers: {
                'Content-Type': 'application/json'
            }
        });
        setFossilState(content);
    }
    return (
        <Editor
            initialValue={rteContent}
            init={{
                selector: ".fossilText",
                menubar: 'file edit view insert format',
            }}
            value={fossilState}
            onEditorChange={updateFossilText}
        />
    )
}

export default App;

Solution

  • What you're looking for is session storage. Reference here.

    Session storage is specific to a tab (session), while local storage is specific to a site.
    Also, I hope you're aware of the storage size limitation (Guess it's 5 MB).