#7.0 Get Selectors #7.1 Set Selectors

SilverAsh·2023년 10월 29일
0

React

목록 보기
14/16

function App() {

  return (
    <div>
      <input type="number" placeholder="Minutes" />
      <input type="number" placeholder="Hours" />
    </div>

  )
}
export default App;

state이 아닌 atom에 저장 and 하나의 데이터만 저장하고싶음

input's value는 type에 관계없이 string 반환.
event.currentTarget.value했을 때 string. => 앞에 + 를 붙여준다. => setMinutes(+event.currentTarget.value)

selector

import { atom, selector } from "recoil";

export const minuteState = atom({
    key: "minutes",
    default: 0,

})

export const hourSelector = selector({
    key: "hours",
    get: ({ get }) => {
        const minutes = get(minuteState);
        return minutes / 60
    }
})

the 'SET' property of selector

const [hours, setHours] = useRecoilState(hourSelector);
useReocilState를 selector와 쓸 때, 반환하는 것 중 첫번째는 get함수가 반환하는 값이고, 두번째(setHours)는 set함수가 반환하는 함수이다.

export const hourSelector = selector<number>({
   key: "hours",
   get: ({ get }) => {
       const minutes = get(minuteState);
       return minutes / 60
   },
   set: ({ set }, newValue) => {
       const minutes = Number(newValue) * 60;
       set(minuteState, minutes);
   }
})
function App() {
  const [minutes, setMinutes] = useRecoilState(minuteState);
  const [hours, setHours] = useRecoilState(hourSelector);
  const onMinutesChange = (event: React.FormEvent<HTMLInputElement>) => {
    setMinutes(+event.currentTarget.value)
  }
  const onHoursChange = (event: React.FormEvent<HTMLInputElement>) => {
    setHours(+event.currentTarget.value)
  }
  return (
    <div>
      <input value={minutes} onChange={onMinutesChange} type="number" placeholder="Minutes" />
      <input value={hours} onChange={onHoursChange} type="number" placeholder="Hours" />
    </div>

  )
}
profile
Frontend developer이자

0개의 댓글