rt2zz / redux-persist

persist and rehydrate a redux store
MIT License
12.91k stars 863 forks source link

Save a reducer when a button is clicked #1364

Open Husdady opened 2 years ago

Husdady commented 2 years ago

Hello, I have a problem that I cannot solve. I have 2 reducers: "products" and "filters". What I want to do is have the "filters" reducer show up in localstorage only when a button is clicked.

// store.js

// Librarys
import thunk from "redux-thunk";`
import storage from "redux-persist/lib/storage";
import { persistStore, persistReducer  } from "redux-persist";
import { combineReducers, createStore, applyMiddleware } from "redux";

// Reducers
import products from "./reducers/client";
import filters from "./reducers/filters";

// Persist config
const rootPersistConfig = {
  key: 'root',
  version: 1,
  storage: storage,
  blacklist: ['filters'],
}

// Reducers
const reducers = combineReducers({
  filters: filters,
  products: products,
});

const persistedReducer = persistReducer(rootPersistConfig, reducers);

function getReduxConfig() {
  const store = createStore(persistedReducer, applyMiddleware(thunk));
  const persistor = persistStore(store);
  return { store, persistor };
}

i am using redux persist along with react and i have this component

// Button.js

import { Component } from "react";

class Button extends Component {

  saveFiltersInLocalStorage() {
    // this function should save the 'filters' in LocalStorage
  }

  render() {
    return (
      <button onClick={this.saveFiltersInLocalStorage.bind(this)}>this is a test button</button>
    )
  }
}

export default Button;

well, when the application renders, the "products" key is shown in LocalStorage, which is fine, the other "filters" key, is not being shown because I add it to the blacklist. So I need some way that when clicking on the button, the filters can be saved in LocalStorage.

But I have no idea how to do this, maybe I would go the easy way of using localstorage directly, saving the state in another key other than "persist:root" but I have implemented this gem, which makes the job much easier. I already made a post on stackoverflow with no result