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

Viewed 211

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?

4 Answers

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>
)

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

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

My version, with custom hook.

import "./styles.css";
import { useState,useEffect } from "react";

function useLocalStorage(key) {
  const [state, setState] = useState(localStorage.getItem(key));
  function setStorage(item) {
    localStorage.setItem(key, item);
    setState(item);
  }
  return [state, setStorage];
}

export default function App() {
  const [input, setInput] = useState("");
  const [item, setItem] = useLocalStorage("myKey");

  return (
    <div className="App">
      <input value={input} onInput={(e) => setInput(e.target.value)} />
      <button onClick={() => setItem(input)}>Click</button>
      <p>{item}</p>
    </div>
  );
}

https://codesandbox.io/s/bitter-sea-d6ni42?file=/src/App.js

Related