Home > Back-end >  How to share a specific variable between different react components
How to share a specific variable between different react components

Time:05-10

I have 2 sibling components home and history where home has the following function

//home
function handledata() {
    const key = uuidv4();
    localStorage.setItem(key, JSON.stringify(formdata));
  }

I need to access local storage in the sibling history component so how do i access this key variable there

//history
const [items, setItems] = React.useState([]);
  const handledata = () => {
    localStorage.getItem(key);
  };

Complete code of both files https://github.com/Megahedron69/testrep

CodePudding user response:

You're best option is to decouple localstorage from both the components & make a it a separate module or a class. Then you can access it in both the files.

Pseudocode

class LocalStorage {

  setItem(key, item) { ... }
  getItem(key) { ... }

}

If you don't want to do that - Lifting the state up is the best possible solution when want to share data between sibling components.

Make a parent component of home & history & use localstorage there.

CodePudding user response:

You don't need handledata function in that case. You can just access localStorage without it:

 const data = localStorage.getItem(key);
 // use this data any way you want in the component
  • Related