sgt_pepper85
sgt_pepper85

Reputation: 441

How to persist individual state values using React Native

I have a button in my react native app which toggles a state value from true to false:

const [isLearned, setIsLearned] = useState(false);

addRemoveCardToLearned = () => {
  setIsLearned(!isLearned);
};

This button can be used on multiple cards within the app, and so each card will always have it's own state for isLearned, either true or false. What I need to do is persist the state value of each individual card after page refresh. I have tried using AsyncStorage with the useEffect hook:

useEffect(() => {
  AsyncStorage.setItem('isLearned', JSON.stringify(isLearned));
}, [isLearned]);

useEffect(() => {
  const storeIsLearned = Boolean(AsyncStorage.getItem('isLearned'));
  setIsLearned(storeIsLearned);
}, []);

But what this does is change all cards state value at once. I also tried inserting a getter function within the code for my button:

addRemoveCardToLearned = () => {
  setIsLearned(!isLearned);

  AsyncStorage.getItem('isLearned').then((isLearned) => {
    console.log(isLearned);
  });
};

But this just records every entry as true.

Since each card will have a different state value is there a way to persist each of them individually?

Upvotes: 0

Views: 404

Answers (1)

Ankit Abhinav
Ankit Abhinav

Reputation: 49

Async storage is global that is why it updates all the cards because all the cards are referring to a single isLearned key valye pair in the Async storage. Adding a unique code to each async storage while saving the state can solve the problem.

<FirstComponent uniqueCode='001' />
<FirstComponent uniqueCode='002' />

prefix the uniqueCode prop to the key name while saving the data to Async Storage, and also while reading from the Async storage.

useEffect(() => {   AsyncStorage.setItem(`${props.uniqueCode}_isLearned`, 
JSON.stringify(isLearned)); }, [isLearned]);

useEffect(() => {   const storeIsLearned = 
Boolean(AsyncStorage.getItem(`${props.uniqueCode}_isLearned`));   
setIsLearned(storeIsLearned); }, []);

Upvotes: 1

Related Questions