skip to Main Content

I want to obtain a value from a variable hosted in redux and memorize it, to later compare it with itself and verify if it is different.

I need, for example, to do the following : const value = useSelector(state => state.data.value); (suppose that here the value is 0) now, when value changes, i need to compare it with the value it had previously

2

Answers


  1. You have to use selectors(i use ‘reselect’ library for that), such as:

    file: selectors.js

    import { createSelector } from 'reselect';
    
    const stateEnvironments = state => state.environments;
    
    export const selectEnvironments = createSelector([stateEnvironments], 
    environments => environments.data);
    

    so then in your component you can use mapStateToProps with reselect and connect

    import { createStructuredSelector } from 'reselect';
    import { connect } from 'react-redux';
    
    // your component here
    const EnvironmentCurrencies = props => {
      const {
        data,
      } = props;
    
      return (
      <div>
      ...
      </div.
      );
    };
    
    
    const mapStateToProps = createStructuredSelector({
      data: selectEnvironments,
    });
    
    // here you can update your values with actions
    // mapDispatchToProps is especially useful for constraining our actions to the connected component.
    // You can access these via `this.props`.
    const mapDispatchToProps = dispatch => ({
      setEnvironment: environment => dispatch(actions.setEnvironment(environment)),
    });
    
    export default connect(mapStateToProps, mapDispatchToProps)(Environments);
    
    

    this is not a full working example and the version that you might use, can have a bit different synaxis, but I hope this gives you a kick start. If not, let me know, I’ll add more extensive example

    Login or Signup to reply.
  2. If you want to check what the value was on the previous render, you can save it in a ref:

    const SomeComponent = () => {
      const value = useSelector(state => state.data.value)
      const prevRef = useRef();
      useEffect(() => {
        // Once the render is complete, update the ref's value
        prevRef.current = value;
      });
      // Do something comparing prevRef.current and value 
    }
    

    If you’re doing this a lot you might find it useful to make a custom hook:

    const usePrevious = (value) => {
      const ref = useRef();
      useEffect(() => {
        ref.current = value;
      });
      return ref.curren;t
    }
    
    // used like:
    const SomeComponent = () => {
      const value = useSelector(state => state.data.value)
      const prev = usePrevious(value);
      // Do something comparing prev and value.
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search