Example)
โก๏ธ ์์์ ๊ฐ์ด get์ ํตํด์ observable์ ์๋ ๊ฐ์ ๊ฐ์ ธ์ฌ ์ ์๋ค.
const News = observable({
searchInput : "",
state : "pending",
data : [],
get Data(){
return this.data;
},
apiRequest : flow(function* (){
try{
const response = yield axios.get(URL, {
headers:{
'X-Naver-Client-Id':Id,
'X-Naver-Client-Secret':Secret,
},
params:{
query : this.searchInput,
}
});
console.log(response);
this.data = response.data.items;
this.state = "done";
}catch(e){
console.log(e);
}
})
โก๏ธ observable state๊ฐ ๋ฐ๋ ๋๋ง๋ค ์๋์ ์ผ๋ก ๋ณํ๋ฅผ ๊ฐ์งํ๊ณ side effects๋ฅผ ์คํํ๋ค.
autorun
์ ์ด์ฉํด์ ๊ตฌํํ ์ ์๋ค. autorun(effect: (reaction) => void)
autorun
์ด ์คํ๋๋ค.Example)
import { makeAutoObservable, autorun } from "mobx"
class Animal {
name
energyLevel
constructor(name) {
this.name = name
this.energyLevel = 100
makeAutoObservable(this)
}
reduceEnergy() {
this.energyLevel -= 10
}
get isHungry() {
return this.energyLevel < 50
}
}
const giraffe = new Animal("Gary")
autorun(() => {
console.log("Energy level:", giraffe.energyLevel)
})
autorun(() => {
if (giraffe.isHungry) {
console.log("Now I'm hungry!")
} else {
console.log("I'm not hungry!")
}
})
console.log("Now let's change state!")
for (let i = 0; i < 10; i++) {
giraffe.reduceEnergy()
}
reaction(() => value, (value, previousValue, reaction) => { sideEffect }, options?)
autorun
๊ณผ ๋น์ทํ์ง๋ง reaction
์ ์ด๊ธฐ์ ์คํ๋์ง ์๋๋ค. Example)
import { makeAutoObservable, reaction } from "mobx"
class Animal {
name
energyLevel
constructor(name) {
this.name = name
this.energyLevel = 100
makeAutoObservable(this)
}
reduceEnergy() {
this.energyLevel -= 10
}
get isHungry() {
return this.energyLevel < 50
}
}
const giraffe = new Animal("Gary")
reaction( // ์ด๊ธฐ์ ์คํ๋์ง ์๊ณ ๊ฐ์ด ๋ณํ๋ ๋ ์คํ๋๋ค.
() => giraffe.isHungry,
isHungry => {
if (isHungry) {
console.log("Now I'm hungry!")
} else {
console.log("I'm not hungry!")
}
console.log("Energy level:", giraffe.energyLevel)
}
)
console.log("Now let's change state!")
for (let i = 0; i < 10; i++) {
giraffe.reduceEnergy()
}
import { observer } from "mobx-react-lite" // Or "mobx-react".
const MyComponent = observer(props => ReactElement)
โก๏ธ observer๋ก ์ปดํฌ๋ํธ๋ฅผ ๊ฐ์ธ์ค๋ค.
observer
์ ๋ฆฌ์กํธ ์ปดํฌ๋ํธ์ observables ๋ค์ subscribeํ๊ฒ ํด์ค๋ค. ๋ฐ๋ผ์ ๊ฐ์ ๋ณํํจ์ ๋ฐ๋ผ ๋ฆฌ์กํธ ์ปดํฌ๋ํธ์์ ๋ ๋๋ง์ด ๋๋ ๊ฒ์ด๋ค.