Reputation: 173
I trying realize do list with React-Redux and have a problem. I don't know how can I put array with deals into localStorage and then get it. I have input where I write deal and than after click button "Add" value puts into array deals and than I map that array. But I don't know how can I put that array into localStorage in Redux. I tryed different variants but they were failed.Now I put all states into localStorage but what I have to do next i don't know.
Maybe if I can somehow get state in action than I can realize that to do list.
reducer
const initialState ={
value: "",
deals: []
}
export default function toDoList(state = initialState, action){
switch(action.type){
case HANDLE_CHANGE:
return {
...state, value: action.value.target.value
}
case ADD_DEAL:
return {
...state, deals: [...state.deals, action.deal], value: ""
}
default:
return state
}
}
action
export function handleChange(value){
return{
type: HANDLE_CHANGE,
value
}
}
export function addDeal(deal){
return{
type: ADD_DEAL,
deal
}
}
export function typeDeal(deal){
return (dispatch) =>{
if(deal == "" || deal == " "){
alert("Please type deal");
}else{
dispatch(addDeal(deal));
}
dispatch(getDealsLocalStorage())
}
}
export function getDealsLocalStorage(){
return (dispatch) =>{
const getlocalStorage = JSON.parse(localStorage.getItem('testLocal'));
const dealsLocal = getlocalStorage.ListInput.deals; //get array with deals from localStorage
}
}
index.js
const composeEnhancers =
typeof window === 'object' &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
}) : compose;
const store = createStore(
Reducer,
composeEnhancers(
applyMiddleware(thunk)
)
)
store.subscribe(()=>{
localStorage.setItem('testLocal', JSON.stringify(store.getState()))
})
Upvotes: 0
Views: 1726
Reputation: 358
You can use redux presistent library which keeps the clone of redux store in localstorage. Here is the command to install npm install redux-persist
If you want to learn more about it please go through this url : https://www.npmjs.com/package/redux-persist
Upvotes: 1
Reputation: 22925
Just initialize state with data from localStorage
let initialState = {
value: "",
deals: []
}
try {
let state = localStorage.getItem('testLocal');
if (state) {
initialState = JSON.parse(state || JOSN.stringify(initialState))
}
catch (e) {
}
export default function toDoList(state = initialState, action){
switch(action.type){
case HANDLE_CHANGE:
return {
...state, value: action.value.target.value
}
case ADD_DEAL:
return {
...state, deals: [...state.deals, action.deal], value: ""
}
default:
return state
}
}
However, I would say, use redux-persist
package
Upvotes: 1