React Persist State to LocalStorage with useEffect

React Persist State to LocalStorage with useEffect

Ben Awad

5 лет назад

53,144 Просмотров

Ссылки и html тэги не поддерживаются


Комментарии:

@varunravalia4141
@varunravalia4141 - 16.01.2023 22:30

Not working for me.
IDK why

Ответить
@arifmuhamadthalhah9043
@arifmuhamadthalhah9043 - 16.12.2022 12:41

short and clear as crystal ,thx very much

Ответить
@melvec1
@melvec1 - 25.11.2022 17:39

my second useEffect is overriting the first one so I am not loading the JSON file as expected. This is my code, any ideas?

import React , {useState} from 'react';
import {generate} from 'shortid'
import '@fontsource/roboto/300.css';
import '@fontsource/roboto/400.css';
import '@fontsource/roboto/500.css';
import '@fontsource/roboto/700.css';

import MyForm from './MyForm';
import { MyTable } from './MyTable';


interface MyObj {
myString: string;
myNumber: number;
}

const App = ()=> {


const [rows, setRows] = useState([{
id: "32",
firstName: "Mel",
lastName: "Vel",
email: "sasasa"
}

]);

React.useEffect(()=> {
const data = localStorage.getItem('myList');
if (data){
console.log('yes data')
setRows(JSON.parse(data));
}
}, [])

React.useEffect(()=> {
console.log('set item rows')
localStorage.setItem("myList", JSON.stringify(rows));
setRows(rows);

});

return (
<div style={{ textAlign: "center"}}>
<MyForm onSubmit={(data)=>{
setRows(currentRows => [
{
id: generate(),
...data
},
...currentRows,

])

}} />
<MyTable
rows={rows }
/>

</div> )
}

export default App;

Ответить
@LilithinMerria
@LilithinMerria - 14.11.2022 18:59

Thank you for this. It helped a lot ^^

Ответить
@ZacharyBetz
@ZacharyBetz - 19.10.2022 23:59

Concise and useful. Thank you sir.

Ответить
@prograamer
@prograamer - 12.10.2022 13:27

Thank you so much

Ответить
@kalivasquezart
@kalivasquezart - 11.06.2022 00:56

My code is exactly the same, but for some reason the local storage data doesn't persist for me between app reloads... any idea why? Could this be browser's fault?

Ответить
@rebeccacano4679
@rebeccacano4679 - 01.06.2022 22:47

thanks!!!! quicky easy solution

Ответить
@Fizzify
@Fizzify - 29.05.2022 03:28

Thank you so much. This helped me.

Ответить
@mohammadjavadaghazadehfard7873
@mohammadjavadaghazadehfard7873 - 12.05.2022 01:49

Hi Ben, Thank you, It was very cool. please make more videos like this. Best of luck 🌹🙏

Ответить
@cjs4912
@cjs4912 - 03.05.2022 04:59

i followed the exact steps but still unable to persist my data

Ответить
@abhiavasthi624
@abhiavasthi624 - 03.03.2022 13:58

I love you ben, you're a lifesaver, i've been struggling with this for a week only to find the solution is so simple, Thank you so much man.

Ответить
@Younes-he7li
@Younes-he7li - 20.02.2022 19:37

Thanks dude

Ответить
@VineetSingh-qg5zt
@VineetSingh-qg5zt - 08.02.2022 00:37

It Worked for me Thanks a lot brother!!!

Ответить
@alirafizadeh8628
@alirafizadeh8628 - 24.01.2022 18:20

i was stuck for three hours on this bloody problem. thanks for the help

Ответить
@rBroneak
@rBroneak - 14.01.2022 03:13

Solid content as always sir.

Ответить
@adnanarnautovic7391
@adnanarnautovic7391 - 04.12.2021 20:15

Thanks man !

Ответить
@ronitpanda5964
@ronitpanda5964 - 31.10.2021 07:01

You are the best keep building startups :-))

Ответить
@seanjoyce2909
@seanjoyce2909 - 25.10.2021 12:32

Great video man. Thanks for the help!

Ответить
@ghackgaming1804
@ghackgaming1804 - 06.09.2021 07:03

thank you so much dude

Ответить
@doomguy2135
@doomguy2135 - 28.08.2021 10:23

thanks king

Ответить
@ianbergia5013
@ianbergia5013 - 26.07.2021 03:42

Thank you so much Ben, yo helped me to resolve an issue in my code

Ответить
@hk_build
@hk_build - 21.07.2021 17:12

What if user data is sensitive and you still need to store in UI what we can use apart from local storage????

Ответить
@hk_build
@hk_build - 21.07.2021 17:11

What if user data is sensitive and you still need to store in UI what we can use apart from local storage????

Ответить
@KaranSharma-ew7io
@KaranSharma-ew7io - 04.07.2021 16:15

artist you are

Ответить
@xEJG112
@xEJG112 - 10.06.2021 22:01

Very helpful video..thank you!!

Ответить
@codehermano8002
@codehermano8002 - 23.05.2021 18:22

Hey there hopefully someone can help me out. I followed the implementation like in the video, everything just works fine. Now I wanted to create a new page /add and put the add function and logic in there, but I’m not able to do the set function or doing the useeffect. What am I missing? I’m thankful for every help!

Ответить
@user-kv5xf8qw7f
@user-kv5xf8qw7f - 09.04.2021 14:06

Thank you, Ben!

Ответить
@bishowpandey8205
@bishowpandey8205 - 07.04.2021 18:54

Thanks man! I was stuck for 10 hours because i was setting item first in the local storage and then getting it and i was getting nothing. I saw your vid and now solved the issue. Thanks again

Ответить
@gellermicael99
@gellermicael99 - 06.04.2021 17:57

fucking brilliant, simple, straight to the point and effortlessly practical. These other videos had me running circles LOL

Ответить
@machadoviewer
@machadoviewer - 31.03.2021 01:09

Thanks, dude!

Ответить
@sonnybrown4758
@sonnybrown4758 - 29.03.2021 18:14

This helps a lot, thank you. But there's no way Kirby is top tier. 1/10

Ответить
@karimdakrouri3410
@karimdakrouri3410 - 17.03.2021 13:13

Hi, hope you are good. I just finished implementing a registration process with multiple screens, what if the app closes in the middle of the process? I wouldnt want the user to start over again. How do i achieve this?

Ответить
@karimdakrouri3410
@karimdakrouri3410 - 17.03.2021 13:13

Hi, hope you are good. I just finished implementing a registration process with multiple screens, what if the app closes in the middle of the process? I wouldnt want the user to start over again. How do i achieve this?

Ответить
@tldrcode
@tldrcode - 11.02.2021 17:30

My hero.

Ответить
@rohan1765
@rohan1765 - 07.02.2021 08:37

Thanks Ben 👍🏻

Ответить
@ishraqkabir8681
@ishraqkabir8681 - 26.01.2021 22:43

or you can use a custom useLocalState hook and store the value in localstorage everytime setValue is called
in addition to that you can add an event on local storage value change and change state via that
in that way a state change in one window will affect that same state in another window of the same browser

Ответить
@Trippze
@Trippze - 24.01.2021 11:12

holy shit thanks!

Ответить
@mikki7522
@mikki7522 - 30.11.2020 16:36

Excellent!

Ответить
@arpielen
@arpielen - 11.11.2020 18:18

This video just saved my life on my internship program! Thank you so much man :D

Ответить
@Captinofthemudslayer
@Captinofthemudslayer - 04.11.2020 07:21

you videos suck ... you skip too many steps

Ответить
@asmereg
@asmereg - 04.10.2020 08:36

TYSM buddy 💛 Keep teaching please

Ответить
@danilsviridenko6565
@danilsviridenko6565 - 02.10.2020 12:51

if somebody want to see normal React (Local Storage)code which was writte with using Functional components here he is:

function App () {

const [state,setState] = React.useState({

user: '',

rememberMe: false

})



const ref = useRef(null)



const handleChange = (event) => {

const input = @t;

const value = input.type === 'checkbox' ? input.checked : input.value;



setState(Object.assign({}, state, {[input.name]: value }));

};





localStorage.setItem('foo', 'foo')

const handleFormSubmit = () => {

const { user, rememberMe } = state;

localStorage.setItem('rememberMe', JSON.stringify(rememberMe));



if (rememberMe) {

localStorage.setItem('user', JSON.stringify(user));

} else {

localStorage.setItem('user', '');

}

};



useEffect( () => {

const rememberMe = localStorage.getItem('rememberMe') === 'true';

const user = rememberMe ? JSON.parse(localStorage.getItem('user')) : '';

setState({ user, rememberMe });

},[])





return (

<form onSubmit={handleFormSubmit} ref={ref}>

<label>

User: <input name="user" value={state.user} onChange={handleChange}/>

</label>

<label>

<input name="rememberMe" checked={state.rememberMe} onChange={handleChange} type="checkbox"/> Remember me

</label>

<button type="submit">Sign In</button>

</form>

);

}

Ответить
@danielchavesdev
@danielchavesdev - 16.09.2020 16:16

Thank you a lot!

Ответить
@stanissamisco3949
@stanissamisco3949 - 28.06.2020 18:37

Great tutorial. Straight to the point, super super simple, super clear
EDIT: and comments. Read the comments guys. Thx

Ответить
@matthewp3709
@matthewp3709 - 19.06.2020 07:16

What would happen if you did this in session storage instead? Does session storage persist across page refresh?

Ответить
@ibrahimalb7601
@ibrahimalb7601 - 02.06.2020 14:56

I have some questions about this approach,

- Can I use this method in production?
- Can I apply this method to save login state? And if not, what is the alternative?

Ответить
@KDcoo
@KDcoo - 17.05.2020 07:03

Wonderful video! Thank you exactly what I was looking for.

Ответить
@nikosspiropoulos8417
@nikosspiropoulos8417 - 14.05.2020 20:53

very good video tutorial. thank you

Ответить
@ivokrustev9253
@ivokrustev9253 - 24.04.2020 16:57

Thank you!

Ответить