How to keep the selected item from select in a react application to be same on reloading the page?
I have to maintain the state as per the last selection by the user on reloading. please help me edit this code so that it works properly on reloading the page with same state.
function handleChangeBranch(value: any) {
AdvertiseService.fetchNewStore(
`${value}`,
(store: any) => {
// brand = store;
setSelectedBranch(store);
},
() => { },
() => { }
);
setBranchChanged(true)
}
<Button className="city-selection-btn">
<Select
defaultValue={branches?.branches?.length === "1" ? selectedBranch?.name : "choose location"}
style={{ width: 120, border: "none" }}
onChange={handleChangeBranch}
>
{branches &&
branches.branches?.map((branch: any) => (
<Option
value={branch.id}
className="advertise-branch-list-item"
key={branch.id}
>
{branch.name}
</Option>
))}
</Select>
</Button>
You can store the selected value on localStorage or URL, then in componentDidMount you can get the value you stored (on localStorage or URL) and set to the state that you bind to the Select component value.
P.S. you can try localStorage without installing any library:
localStorage.getItem("branch") to get data
localStorage.setItem("branch", value) to set data