'How to render component as soon as the value stored in local in React

I want to show one component only if a value ('id') is stored in the localStorage. And id is stored when the button is clicked.

{localStorage.getItem('id') != null ? <Game/> : null }

It works fine, so I click the button and store the id in localStorage but only after I refresh I am able to see component. But I want to render the component as soon as it is stored in local (refresh the page shouldnt be needed)

Any suggest to do it?



Solution 1:[1]

components usually render with the state change. you can bind one state for local storage (if u need local storage anyway) and just update the state each time. if you want to store in local storage then take value from the state.

example:

const [userid, setUserId] = useState(localStorage.getItem('id'));


const onSave : (value) => {
   localStorage.setItem('id', JSON.stringify(value))
   setUserId(value)
}

return (
    <div>
       {userid != null ? <Game/> : null }
    </div>
)

Solution 2:[2]

You have to use state management, the local storage has updated but your DOM is unaware of it, to fix this check the following example

for this we use the useState hook, here we initialize the idLocal value with the value from local storage

  let [idLocal, setIdLocal] = useState(localStorage.getItem("id"));

then you have to use this value for the condition as changes to this value will be visible in DOM , the setIdLocal is used to set or update this idLocal

{idLocal? <Game/> : null }

for updating the value on the button click

 <button onClick={()=>setLocalstore()}>Off</button>

setLocalstore =()=>{
setIdLocal(whatever value you want)
}

check out this minimal example https://codesandbox.io/s/react-hooks-usestate-forked-5j6ck0?file=/src/index.js:567-605

Solution 3:[3]

1.Initiate state:

const [id, setId] = useState(
  localStorage.getItem('id') ? <Game/> : null
);

2.Save every change inside local storage:

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

3.Render component using state

Solution 4:[4]

Parse the XML output from netsh wlan export profile instead:

# create a temporary folder for `netsh` to export to
$tmpFolderName = [System.IO.Path]::GetRandomFileName()
$tmpFolder = New-Item -Name $tmpFolderName -Type Directory

try {
  # export config to folder
  netsh wlan export profile name=(Get-NetConnectionProfile -InterfaceAlias WLAN).Name folder="$($tmpFolder.FullName)" key=clear 

  # parse resulting XML config
  $profileConfig = [xml]($tmpFolder |Get-ChildItem -Filter *.xml |Get-Content -Raw)

  # output key
  $profileConfig.WLANProfile.MSM.Security.sharedKey.keyMaterial
}
finally {
  # clean up
  $tmpFolder |Remove-Item -Recurse -Force
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Faizal Hussain
Solution 3 Moein moeinnia
Solution 4 Mathias R. Jessen