Skip to content
Snippets Groups Projects
Select Git revision
  • 4ebc81f1959e1fe8f7c0265bdb29d77bdd381194
  • main default protected
2 results

unitSelector.js

Blame
  • Forked from SOFT Core / SOFT 260 / React Redux Starter Code
    Source project has a limited visibility.
    unitSelector.js 1.54 KiB
    import { store } from '../../app/store';
    import { useDispatch } from 'react-redux';
    import {
      setCurrentInputUnit,
      setCurrentOutputUnit,
    } from './unitSelectorSlice';
    import PropTypes from 'prop-types';
    
    export function UnitSelector(props) {
      // type will either be 'Input' or 'Output'
      UnitSelector.propTypes = {
        type: PropTypes.string.isRequired,
      };
    
      const unitSelectorOptions = [
        {
          label: 'Km',
          value: 'km',
        },
        {
          label: 'M',
          value: 'm',
        },
        {
          label: 'Cm',
          value: 'cm',
        },
        {
          label: 'Ft',
          value: 'ft',
        },
        {
          label: 'In',
          value: 'in',
        },
      ];
    
      const disbatch = useDispatch();
      function handleChange(e) {
        const unsubscribe = store.subscribe(() =>
          console.log('State after dispatch: ', store.getState()),
        );
        const currentUnit = e.target.value;
        console.log(currentUnit);
    
        if (props.type === 'Input'){
          disbatch(setCurrentInputUnit(currentUnit));
        }
        if (props.type === 'Output'){
          disbatch(setCurrentOutputUnit(currentUnit));
        }
        unsubscribe();
      }
    
      function handleSubmit(e) {
        e.preventDefault();
      }
    
      return (
        <div>
          <form onSubmit={handleSubmit}>
            <div className="select-container">
              <select name="units" onChange={handleChange}>
                {unitSelectorOptions.map((option) =>
                  <option value={option.value}>{option.label}</option>)}
              </select>
            </div>
          </form>
        </div>
      );
    }