연락처 검색 기능

이시원·2022년 9월 14일
0

Redux 공부

목록 보기
6/12
post-thumbnail

Redux를 사용한 연락처 검색 기능

  • Component

let [keyword, setKeyword] = useState("");
  
let dispatch = useDispatch();

const searchByName = (e) => {
    e.preventDefault();
    dispatch({ type: "SEARCH_BY_USERNAME", payload: { keyword } });
};

  return (
    <Form onSubmit={searchByName} className="search-form">
      <Row>
        <Col>
          <Form.Control
            type="text"
            placeholder="이름을 입력하세요"
            onChange={(e) => setKeyword(e.target.value)}
          />
        </Col>
        <Col>
          <Button type="submit">찾기</Button>
        </Col>
      </Row>
    </Form>
  ); 

  • Reducer

const initialState = {
  contact: [],
  keyword: "",
};

const contactReducer = (state = initialState, action) => {
  let { type, payload } = action;

  switch (type) {
    case "ADD_CONTACT":
      return {
        ...state,
        contacts: [
          ...state.contacts,
          { name: payload.name, phoneNumber: payload.phoneNumber },
        ],
      };
    case "SEARCH_BY_USERNAME":
      return { ...state, keyword: payload.keyword };
    default:
      return state;
  }
};

export default contactReducer;

  • Components

const ContactList = () => {
  const { contact, keyword } = useSelector((state) => state);
  let [filteredList, setFilteredList] = useState([]);

  useEffect(() => {
    if (keyword !== "") {
      // keyword가 들어간 이름들로 이뤄진 새로운 배열 반환하기
      let list = contact.filter((item) => item.name.includes(keyword));
      setFilteredList(list);
    } else {
      setFilteredList(contact);
    }
  }, [keyword]);

  return (
    <div>
      <SearchBox />
      <div className="contact-list">
        연락처 수 : {contact.length}
        {filteredList.map((item) => (
          <ContactItem item={item} />
        ))}
      </div>
    </div>
  );
};

export default ContactList;


profile
코딩공부

0개의 댓글