Search code examples
reactjsnext.jsmobx

Create a counter using next and mobx


i'm trying to create a simple counter using nextjs and mobx. But i got an error. what am I doing wrong? I checked everything a thousand times

import React from "react";
import { observable } from "mobx";
import { observer } from "mobx-react";

@observer
class Counter extends React.Component {
  @observable count = 0;

  increment = () => this.count++;
  decrement = () => this.count--;

  render() {
    return (
      <div>
        {this.count}
        <button onClick={this.increment}>+1</button>
        <button onClick={this.decrement}>-1</button>
      </div>
    );
  }
}

export default Counter;

error -

Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
TypeError: Cannot read properties of null (reading 'useState')

Solution

  • React.Component is a deprecated way of creating components, so if you are making something new and not adding support for legacy stuff I would suggest not to use it.

    To make a local observable you can use useLocalObservable hook, e.g. example of timer from the docs:

    import { observer, useLocalObservable } from "mobx-react-lite"
    import { useState } from "react"
    
    const TimerView = observer(() => {
        const timer = useLocalObservable(() => ({
            secondsPassed: 0,
            increaseTimer() {
                this.secondsPassed++
            }
        }))
        return <span>Seconds passed: {timer.secondsPassed}</span>
    })
    

    I think it will be trivial to translate it to your counter example.

    More info here