简体   繁体   中英

How do I retrieve localStorage data on React app start and store it in Redux using useEffect? (It keeps wiping out my data)

Edit: perhaps I should not combine React hooks and mapStateToProps in the same application, but instead use the Redux hooks (useSelector, etc)?

In my React application I have an array of 'friend' data in Redux. I am using useEffect in one of my components to store this data to browser localStorage every time it changes.

// 'friends' is an array from Redux store,
// storeManyFriends is an action creator that will store to Redux
  const {friends, storeManyFriends} = props;

// store 'friends' to local storage each time it changes
useEffect(() => {
    try {
      persistData(friends,'my friends') // stores to local storage
    } catch (e) {
      console.log('error persisting data',e.message)
    }
  }, [friends]);

I want to load that data from localStorage when the app starts (if it exists) and store it in Redux using useEffect .

useEffect(() => {
// get stored 'friends' from local storage on component mount
    const storedFriends = retrievePersistedData('my friends') 
    if (storedFriends) {
      try {
        storeManyFriends(storedFriends)
      } catch (e) {
        console.log('error retrieving data',e.message)
      }
    }
   }, []);

The problem is that it seems that when the app restarts, the first useEffect is getting called with an empty friends array, which is then stored to localStorage, wiping out what's there. I could check for whether the array is empty before I store it, but sometimes the array will be empty because someone has no friends and I would want to store that empty value. What is the best way to handle this?

For reference, the Redux store initial state would be

export const originalState = {
  friends: [],
};

There are 3 scenarios:

  • no key in localStorage
  • empty array
  • array with data

When you fetch, create the empty array first if it doesn't yet exist. This will ensure that when you save you always have a key (with an empty array).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM