{"size": 1976, "ext": "js", "max_stars_repo_path": "src/pages/10-use-reducer.js", "max_stars_repo_name": "mattclough1/hooks-demo", "max_stars_repo_stars_event_min_datetime": "2019-02-21T14:58:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-21T15:07:48.000Z", "max_issues_repo_path": "src/pages/10-use-reducer.js", "max_issues_repo_name": "mattclough1/hooks-demo", "max_issues_repo_issues_event_min_datetime": "2019-12-27T15:52:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T10:59:19.000Z", "max_forks_repo_path": "src/pages/10-use-reducer.js", "max_forks_repo_name": "mattclough1/hooks-demo", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 2, "max_issues_count": 5, "max_forks_count": null, "avg_line_length": 26.3466666667, "max_line_length": 78, "alphanum_fraction": 0.4984817814}
import React, { useState, useReducer } from 'react';
import Layout from '../components/Layout';
import '../styles/styles.css';

const initialState = [
  'some metal',
  'huge diamonds',
  'a toothpick in my pocket from a long time ago that pokes my leg sometimes',
];

function thingsReducer(state, action) {
  switch (action.type) {
    case 'addThing':
      return [...state, action.payload];
    case 'removeThing': {
      const newState = [...state];
      newState.splice(action.payload, 1);
      return newState;
    }
    default:
      return state;
  }
}

const UseReducerComponent = () => {
  const [state, dispatch] = useReducer(thingsReducer, initialState);
  const [newThing, setNewThing] = useState('');

  return (
    <Layout>
      <div style={{ width: '100%' }}>
        <b>All your favorite things:</b>
        {state.map((thing, ix) => (
          <div key={thing}>
            <div className="spacer-m" />
            <div className="between-row">
              <div>{thing}</div>
              <div className="spacer-sm" />
              <button
                className="input"
                onClick={() => dispatch({ type: 'removeThing', payload: ix })}
                type="button"
              >
                Remove
              </button>
            </div>
          </div>
        ))}
        <hr className="thick-rule" />
        <div>
          <b>Add a thing:</b>
          <div className="spacer-m" />
          <div>
            <input
              className="input"
              type="text"
              value={newThing}
              onChange={({ target }) => setNewThing(target.value)}
            />
          </div>
          <div className="spacer-sm" />
          <button
            className="input"
            onClick={() => dispatch({ type: 'addThing', payload: newThing })}
          >
            Add Thing
          </button>
        </div>
      </div>
    </Layout>
  );
};

export default UseReducerComponent;
