I have following action in redux action.js file,
export const removeActiveLayer = (id) => (dispatch) => {
dispatch({
type: REMOVE_ACTIVE_LAYER,
payload: id,
});
};
my reducer.js file is as below,
case REMOVE_ACTIVE_LAYER:
return {
...state,
activeLayers: state.activeLayers.filter((l) => action.payload !== l.id),
};
I tried to remove the layer from the RemoveLayer.js file as below,
this.props.removeLayer(55);
The layer is removed successfully. There is no issue. My question is, How can I get that id=55 from another file Layers.js?
I have tried to get it in ComponentDidUpdateProps as below,
componentDidUpdate(prevProps, prevState) {
const { removeActiveLayer } = this.props;
if (removeActiveLayer) {
console.log(removeActiveLayer);
}
}
It is just a function, but actually, I need a removed id. Any help will be highly appreciated.
You need to save the removed id in redux state as well if you want to access it in the some other component.
So your reducer.js file would become:
case REMOVE_ACTIVE_LAYER:
return {
...state,
removedId: action.payload,
activeLayers: state.activeLayers.filter((l) => action.payload !== l.id),
};
And now you can access the removedId as a prop from any other component you want:
componentDidUpdate(prevProps, prevState) {
const { removedId } = this.props;
if (removedId) {
console.log(removedId);
}
}
Since at state you already have activeLayers, just simply add a new sub state called lastRemovedLayer. Your state will look like this:
state = {
// others,
activeLayers: [],
lastRemovedLayer: null, // it will be your layer id
}
then at reducer
case REMOVE_ACTIVE_LAYER:
return {
...state,
activeLayers: state.activeLayers.filter((l) => action.payload !== l.id),
lastRemovedLayer: l.id
};
Now you can access this last removed layer in any component at any moment/lifecycle you wish