I'm new to React Redux. Can you tell me how to manually write the below saveUserFilter function? I don't want to use redux-persist-transform-filter anymore as it's using lodash.set, which is vulnerable to Prototype Pollution.
const saveUserFilter = createFilter('user', [
'username',
'displayName',
'timeZone',
])
const persistConfig = {
key: KEY,
storage,
whitelist: [
'user',
'timeZones',
],
transforms: [ saveUserFilter ],
}
Glad to see you! I know how you feel about lodash.set
which is used in redux-persist-transform-filter
can be vulnerable to prototype pollution, especially when considering the cases when object assignment uses Object.create(). But don’t worry because there is an easy method that can help you get rid of this method when saving user filters by making use of the following.
First, let’s define the saveUserFilter
function. This function will manually filter the user
state to include only the properties you need: username
, displayName
, and timeZone
.
Here’s how you can do it:
import { createTransform } from 'redux-persist';
const saveUserFilter = createTransform(
// Transform state before it's serialized and persisted.
(inboundState, key) => {
if (key === 'user') {
// Only include specific properties in the persisted state.
const { username, displayName, timeZone } = inboundState;
return { username, displayName, timeZone };
}
return inboundState;
},
// Transform state being rehydrated.
(outboundState, key) => {
return outboundState;
},
// Specify which reducer this transform applies to.
{ whitelist: ['user'] }
);
const persistConfig = {
key: 'root',
storage,
whitelist: ['user', 'timeZones'],
transforms: [saveUserFilter],
};
export default persistConfig;
redux-persist
's createTransform
to define a custom transformation.username
, displayName
, timeZone
) we need from the user
state.user
reducer in the whitelist so that this transform is applied only to it.For more details on creating transforms with redux-persist
, you can check out the official documentation.
Feel free to reach out if you have any more questions or need further help. Good luck with your project!