Reputation: 143
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.
Upvotes: 0
Views: 1911
Reputation: 626
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.
Upvotes: 2