Is there a way to set/get the entire localState of a component?
Is your feature request related to a problem? Please describe. I want to be able to see (and hopefully set) the entire state of a component.
Describe the solution you'd like To be able to get and set the entire localState of a component.
I'm trying to persist the entire state of a component into a variable to be able to retrieve it but it's not returning the state.
import React, { useState } from "react";
function LocalStateComponent() {
const [checked, setChecked] = useState(false);
return (
<div>
<input
type="radio"
value={checked}
id="radio-local"
title="Radio Local"
name="Radio Local"
onChange={(e) => setChecked(e.target.checked)}
/>
<label for="radio-local">Radio Local</label>
</div>
);
}
function OtherComponent() {
return <div>Not Radio Local</div>;
}
const components = [<LocalStateComponent />, <OtherComponent />];
function App() {
const [index, setIndex] = useState(0);
const component = components[index];
const switchComponent = () => {
console.log("Component", component);
setIndex(index === 0 ? 1 : 0);
};
return (
<div>
<button onClick={switchComponent}>Switch</button>
{components[index]}
</div>
);
}
export default App;
So, in this case, if user clicks on the radio then clicks on switch twice, the radio button should still be clicked.
Here's a video of the wanted behavior:
I wan't to store a component full state as a variable and store it somewhere (localStorage or Redux store) but I need it to be the entire state (or entire component).
With this, it would be possible to persist state between navigations without having to use redux in all of the components.
https://user-images.githubusercontent.com/109171426/180578616-bb001f1f-83e7-4d11-aef1-d14b52fac70e.mp4
In the video, I select a radio button from component A and stores it to localState of component using useState.
Then on Switch button I unmount him and replace it for a new component, when I mount him again, I wanted to be able to retrieve the localState to the component.