Reputation: 301
How to update a component by changing localstorage from another component? for example with react hooks I want to call a function by changing localstorage value, but doesn't work:
React.useEffect(() => {
//call a function by changing id value in localstorage
}, [localStorage.getItem("id")])
Upvotes: 5
Views: 3366
Reputation: 6734
You need to use ContextProvider to share same hooks and data between different components.
import React, { useContext, useEffect, useState } from 'react';
import PropTypes from 'prop-types';
const MyContext = React.createContext();
const useMyHookEffect = (initId) => {
const [id, setId] = useState(initId);
const saveId = (id) => {
window.localStorage.setItem('id', id);
setId(id);
};
useEffect(() => {
//Now you can get the id from the localStorage
const myId = window.localStorage.getItem('id');
setId(myId);
}, []);
return { id, saveId };
};
// Provider component that wraps app and makes themeMode object
export function MyHookProvider({ children, id }) {
const myEffect = useMyHookEffect(id);
return (
<MyContext.Provider value={myEffect}>
{children}
</MyContext.Provider>
);
}
MyHookProvider.defaultProps = {
children: null,
id: null,
};
MyHookProvider.propTypes = {
children: PropTypes.node,
id: PropTypes.string,
};
export const useMyHook = () => useContext(MyContext);
And you need to call it as provider outside of your components.
<MyHookProvider>
<ComponentA />
<ComponentB />
</MyHookProvider>
Now you can use shared hook between your components.
export function ComponentA(){
const { id, saveId } = useMyHook(null);
return (<div>{id}<button onClick={() => saveId(2)}></button></div>);
}
Upvotes: 5
Reputation: 2877
You can use window.addEventListener('storage ...
React.useEffect(() => {
function example() {
//call a function by changing id value in localstorage
}
window.addEventListener('storage', example)
return () => window.removeEventListener('storage', example)
} , [ ])
inside example
you might check that id
is the localStorage
piece make the function run
Upvotes: 0
Reputation: 33
As you want to re-render an element you should use states. By using states every element using this variable will automatically update. You can use the hook useState().
import React, { useState, useEffect } from 'react';
const [ id, setId ] = useState(initalValue);
useEffect(() => {
setId(localStorage.getItem('id'));
}, [localStorage.getItem('id')]);
return(
'Your code and the element that should update'
);
Upvotes: -3