Reputation: 237
I have an API endpoint that returns authenticated user data with a list of phone numbers that are saved to local storage and also a component that fetches the phone numbers from the local storage. I want to update the local storage when a phone number is selected by changing the index of the selected phone number to 0. Please how do I achieved this?
My code below.
Userdata in localstorage
useraccount {
accounts: [
0: {phone: "010475758585"}
1: {phone:"090839494404" }
]
}
Component
const{useraccount: {accounts}} = isAuthenticated()
**// Endpoint below is dependent on the selected phone number**
const getUserTransactions =() =>{
axios.get(`http://example/transactions/${accounts[0]?.phone}`,{
headers: {
'Authorization': `Bearer ${token}`
}
}).then((res)=>{
if(res.data){
console.log(res.data);
setFetchingTransactions(res.data)
}else{
console.log("failed")
}
})
}
useEffect(() => {
getUserTransactions()
}, []);
return (
<>
<h3>Select an phone</h3>
<ul>
{accounts && accounts.map((item, id) => (
<li key={id}>
<h3>{item.phone}</h3>
</li>
))}
</ul>
<Button type="submit" >
Select
</Button>
</>
)
Upvotes: 1
Views: 83
Reputation:
You can update your local storage by just setting the value for the key again.
Like :
foo.jsx
class foo extends React.Component {
constructor(){
localStorage.setItem("foo", "foo");
}
updateStorage = (val) => {
localStorage.setItem("foo", val);
}
render(){
return(
<div>
<button onClick="() => this.updateStorage("foobar")">Update storage</button>
<h3>{{ localStorage.getItem("foo") }}</h3>
</div>
)
}
}
Upvotes: 0
Reputation: 1070
useHooks has a very useful hook for this called useLocalStorage
. See https://usehooks.com/useLocalStorage/
you would use it like this
const [transactions, setTransactions] = useLocalStorage('transactions', []);
useEffect(() => {
const newTransactions = getUserTransactions();
setTransactions(newTransactions);
}, []);
Upvotes: 2