<div id = "root"></div>
/*
* https://frontendeval.com/questions/shopping-list
*
* Create a shopping list app with autocomplete item entry
*/

import React, { useEffect, useState }  from "https://cdn.skypack.dev/react@17.0.1";
import * as ReactDOM from "https://cdn.skypack.dev/react-dom@17.0.1";
import axios from "https://cdn.skypack.dev/axios@0.26.1";

const ShoppingList = () => {
  const [inputValue, setInputValue] = useState('');
  const [suggestions, setSuggestions] = useState([]);
  const [list, setList] = useState([]);

  useEffect(() => {
    if (!inputValue.length) {
      setSuggestions([]);
    }
    let timerId = setTimeout(async () => {
      if (inputValue.length > 1) {
        const response = await axios.get(
          `https://api.frontendeval.com/fake/food/${inputValue}`
        );
        setSuggestions([...response.data]);
      }
    }, 500);

    return () => clearTimeout(timerId);
  }, [inputValue]);

  const handleDelete = (index) => {
    list.splice(index, 1);
    setList([...list]);
  };

  const handleCheckbox = (index) => {
    const newList = [...list];
    newList[index].isChecked = !newList[index].isChecked;
    setList(newList);
  };

  return (
    <>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      {!!suggestions.length && (
        <>
          {suggestions.map((item, index) => {
            return (
              <p
                key={index}
                style={{ cursor: 'pointer' }}
                onClick={(e) => {
                  setList([
                    ...list,
                    { name: e.target.textContent, isChecked: false },
                  ]);
                }}
              >
                {item}
              </p>
            );
          })}
        </>
      )}
      <div>
        <h2>Shopping List</h2>
        {list.length ? (
          list.map((item, index) => (
            <p
              key={index}
              style={{
                textDecoration: item.isChecked ? 'line-through' : 'none',
                color: item.isChecked ? 'grey' : '',
              }}
            >
              <input onChange={() => handleCheckbox(index)} type="checkbox" />{' '}
              {item.name}{' '}
              <span
                style={{
                  cursor: 'pointer',
                  color: 'red',
                }}
                onClick={() => handleDelete(index)}
              >
                X
              </span>
            </p>
          ))
        ) : (
          <u>Nothing here!</u>
        )}
      </div>
    </>
  );
};


ReactDOM.render(<ShoppingList />, document.getElementById('root'));
View Compiled
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.