Is there a way to efficiently fetch localStorage data upon launching a React application and seamlessly store it in Redux using the useEffect hook without experiencing any data loss issues?

Should I avoid mixing React hooks and mapStateToProps in my application and instead use Redux hooks like useSelector?

In my React app, I have an array of 'friend' data stored in Redux. Using useEffect in one of my components, I am saving 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 the localStorage data when the app starts 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 issue is that on app restarts, the first useEffect is being called with an empty 'friends' array, which then overwrites the localStorage data. Checking for an empty array before storing it might not be ideal since an empty array could also be a valid case. How can I best handle this situation?

For your information, the initial state of the Redux store would be:

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

Answer №1

There are three different situations to consider:

  • If there is no key stored in localStorage
  • An empty array is present
  • An array that contains data

Always make sure to create an empty array when fetching data if it doesn't already exist. This will guarantee that when saving, a key with an empty array will always be available.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Uploading with Javascript CORS consistently ends with an error event occurring

My current challenge is uploading a file to a server using JavaScript in compliance with the CORS specification. While there are numerous examples available online that successfully upload the file, I encounter an error as the final event being fired. Up ...

Is there a way to trigger a JavaScript function upon checking a checkbox?

Is there a way to trigger a Javascript function when a checkbox within a gridview is checked? protected void ChangeStatusSevenDays_Click(object sender, EventArgs e) { for (int i = 0; i < grdImoveis2.Rows.Count; i++) { GridViewRow RowVie ...

Having issues with incorporating a component into another component in VueJS

Having spent approximately 30 hours on diving into VueJS, I am encountering some difficulties when it comes to using a component within another component. Seeking assistance from someone knowledgeable in this area to provide me with some clarification. Pr ...

The TypeScript error message states that a value of 'undefined' cannot be assigned to a type that expects either a boolean, Connection

I've been grappling with this code snippet for a while now. It was originally written in JavaScript a few months back, but recently I decided to delve into TypeScript. However, I'm struggling to understand how data types are properly defined in T ...

Ways to verify if an array contains two identical object values?

I am in search of a way to determine whether my array contains duplicate object values or not. Let's say I have the following array of objects: const array = [ { id: "id1", quantity: 3, variation: "red", ...

Accessing form data from Ajax/Jquery in php using $_POST variables

Thank you in advance for any assistance on this matter. I'm currently attempting to utilize Ajax to call a script and simultaneously post form data. While everything seems to be working correctly, the $POST data appears to come back blank when trying ...

What You See Is What You Get - A versatile tool for editing both text and

As a developer, I have encountered a common need that StackOverflow addresses. Situation I am in the process of creating a website where users can post code examples and articles using an admin system. These posts may be created by me or registered fron ...

When utilizing KineticJS on a canvas that has been rotated with css3, the functionality of the events appears to be malfunctioning

Currently, I'm working on a rotating pie-chart widget using Kineticjs. However, I have run into an issue where the events don't seem to function correctly when drawing on a rotated canvas element (with the parent node being rotated 60deg using CS ...

How to access a Selenium element using JavaScriptExecutor

My task involves working with a collection of elements in Selenium, specifically located using the By.CssSelector method: var contentRows = new List<TableRow>(); for (var i = 1; i < PositiveInfinity; i++) { var cssSelectorToFind = $"tbody &g ...

How to Use Google Calendar API to Retrieve Available Time Slots for a Given Day

Is there a way to extract the list of available time slots from my Google Calendar? Currently, I am only able to retrieve the list of scheduled events. I am utilizing the Google Calendar npm package. google_calendar.events.list(calObj.name,{ timeMin ...

Identifying and capturing changes in child scope events or properties in Angular

I am encountering an issue with my form directive where I need to intercept ng-click events nested within varying child scopes of the form element. However, I am struggling to hook into these events or child scope properties in a generic way. For demonstr ...

Having trouble with jQuery validation: Seeking clarification on the error

I have implemented some validations on a basic login page and added jQuery validation upon button click. However, the code is not functioning as expected. I have checked the console for errors but none were displayed. Here is the code for your review: ...

JavaScript - issue with event relatedTarget not functioning properly when using onClick

I encountered an issue while using event.relatedTarget for onClick events, as it gives an error, but surprisingly works fine for onMouseout. Below is the code snippet causing the problem: <html> <head> <style type="text/css"> ...

extract the key identifier from the JSON reply

My JSON ResponseData example for form0 is provided below: { "MaterialType": "camera", "AssetID": 202773, "forms": [ { "release": "asyncCmd/accessCameraMulti", "action": "rest/Asset/202773/cameraAccessMultiple", ...

Sophisticated web applications with Ajax functionalities and intricate layouts powered by MVC frameworks

I am looking to integrate an ajax-driven RIA frontend, utilizing JQuery layout plugin (http://layout.jquery-dev.net/demos/complex.html) or ExtJs (http://www.extjs.com/deploy/dev/examples/layout/complex.html), with... a PHP MVC backend, potentially using ...

What is the best way to duplicate an entire webpage with all its content intact?

Is it possible to copy an entire page including images and CSS using Selenium? Traditional methods like ctrl + a or dragging the mouse over the page do not seem to work. How can this be achieved with Selenium without requiring an element to interact with? ...

The Javascript code is not running due to the XSS security measures in place

Within my Wordpress website, I have crafted an HTML form that enables users to view database records corresponding to their input. Following this AJAX tutorial on w3schools, a JavaScript function was implemented to send a GET request to a PHP script on the ...

Utilizing Vue to send information to the POST function

I am encountering an issue with passing data to the Vue.js post method. I am using vue-resource and according to the documentation, it should be structured like this: this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCall ...

conceal elements using the <option> class隐藏

Although it seems like a simple task, I'm struggling to make it work. I created a form where the user can select a month from a list using the tags: <select> <option> When the selection is changed, the class .gone from the day SELECT is ...

Is it possible to create Firebase real-time database triggers in files other than index.js?

Is it possible to split a large index.js file into multiple files in order to better organize the code? Specifically, can Firebase triggers be written in separate JavaScript files? If so, could you please provide guidance on how to do this properly? child. ...