0

For example i have some txt file with JSON data:

"assets": [
           {    
              "id": 1,
              "name": "Mike",
              "contract": "N23421",
              "about": teacher      
           },
           {
              "id": 2,
              "name": "Helen",
              "contract": "N43212",
              "about": teacher  
           }
         ]

Usually i upload/parse this file from server by using Redux.

At that moment i need fetch upload same file from my local storage. So, how can i do this by using Actions and Reducers for local file? I would be grateful for any help or suggestions.

1 Answer 1

2

I would suggest either using some local storage middleware similar to how redux-api-middleware works. Except you wouldn't be fetching data from a server you would be simply retrieving it from local storage. This could easily be extended to save data as well. The idea here is that you would dispatch different actions based on what stage of the request you are in.

e.g.

LOCAL_STORAGE_RETRIEVE_PENDING
LOCAL_STORAGE_RETRIEVE_SUCCESS
LOCAL_STORAGE_RETRIEVE_FAILURE

The success action would contain the retrieved JSON data.

Alternatively, you could access local storage directly in your action creator.

Here is a very simple example written in typescript. You would also need to add a reducer that responds appropriately to the dispatched actions. Note for this example to work you will need to have added redux-thunk middleware.

const localStorageRequest = () => ({
    type: 'LOCAL_STORAGE_REQUEST'
});

const localStorageDataRetrieved = (data) => ({
    type: 'LOCAL_STORAGE_DATA_RETRIVED'
    data,
});


export const getDataFromLocalStorage = (key: string) =>  (dispatch: Dispatch<any>) => {
    // This action might be used to change some state to pending or fetching.
    dispatch(localStorageRequest());
    const data = localStorage.getItem(key);
    dispatch(localStorageDataRetrieved(data));
};

The simpler solution, for now, would be to do this within your action creators. You could add middleware later as your application grows.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for suggestion but could you explain how works yours const localStorageDataRetrieved = (data) => ({ type: 'LOCAL_STORAGE_DATA_RETRIVED' data, }); i'm right understand that data: payload.data?
@vvn92 data will be the value retrieved from local storage and passed in as a parameter. In the example I'm using a property value shorthand available in es6. When the the property name matches the value name, you can omit the property name. See eventbrite.com/engineering/… for more information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.