0

I am new to React and Mobx and am following an online tutorial.

The tutorial says to use reaction eg:

reaction(() => list.totalPrice, () => changed++)

But I just get the error ReferenceError: reaction is not defined.

I'm not sure what this means or how to go about making it work (can't find anything about it on Google or SO).

According to the Mobx documentation, I seem to be using it correctly https://mobx.js.org/refguide/reaction.html

Would anyone know what this means?

My complete code is:

import { getSnapshot, onSnapshot, onPatch } from "mobx-state-tree"
import { WishList, WishListItem } from "./WishList"

it("can create a new instance of a model", () => {
  const item = WishListItem.create({
    name: "some item name",
    price: 28.74,
  })

  expect(item.price).toBe(28.74)
  expect(item.image).toBe("")
  item.changeName("Narnia")
  expect(item.name).toBe("Narnia")

})

it("can create a wishlist", () => {
  const list = WishList.create({
    items: [
      {
        name: "another item name",
        price: 30.43
      } 
    ]
  })

  expect(list.items.length).toBe(1)
  expect(list.items[0].price).toBe(30.43)
})

it("can add new item to list", () => {
  const list = WishList.create()
  const states = []
  onSnapshot(list, snapshot => {
    states.push(snapshot)
  })

    list.add({
      name: "A new item",
      price: 10
    }
  )

  expect(list.items.length).toBe(1)
  expect(list.items[0].name).toBe("A new item")
  list.items[0].changeName("Hello world")
  expect(list.items[0].name).toBe("Hello world")

  expect(getSnapshot(list)).toMatchSnapshot()

  expect(states).toMatchSnapshot()

})


// Patches
it("can add new item to list - 2", () => {
  const list = WishList.create()
  const patches = []
  onPatch(list, patch => {
    patches.push(patch)
  })

    list.add({
      name: "A new item",
      price: 10
    }
  )

  list.items[0].changeName("Hello world 2")

  expect(patches).toMatchSnapshot()

})

// Views
it("can calculate the total price of a wishlist", () => {
  const list = WishList.create({
    items: [
      {
        name: "Machine gun preacher",
        price: 11,
        image: ""
      },
      {
        name: "lego",
        price: 100,
        image: ""
      }
    ]
  })

  expect(list.totalPrice).toBe(111)

  let changed = 0
  reaction(() => list.totalPrice, () => changed++)

  expect(changed).toBe(0)
  console.log(list.totalPrice)
  list.items[0].changeName("test")
  expect(changed).toBe(0)
  list.items[0].changePrice(10)
  expect(changed).toBe(1)

})
skyboyer
  • 22,209
  • 7
  • 57
  • 64
MeltingDog
  • 14,310
  • 43
  • 165
  • 295

1 Answers1

0

The tutorial excluded the part about adding

import { reaction } from "mobx"

MeltingDog
  • 14,310
  • 43
  • 165
  • 295