Mobx modifies data in non-react components, modifies data in ts/js to achieve responsive update

When we encapsulated mobx as data storage before, we used useContext as a package, turned the store into a hooks, and encapsulated the code:

import React from 'react'
import UserInfo from './user'
import Setting from './seting'
import NoteStore from './note'

class Store {
    userInfo: UserInfo
    setting: Setting
    noteActive: NoteStore

    constructor() {
        this.userInfo = new UserInfo()
        this.setting = new Setting()
        this.noteActive = new NoteStore()
    }
}

// 使用context是为了让react识别到Store里面的mobx,不然react不认识Store
export const rootStore = new Store()
const context = React.createContext(rootStore)
export const useStore = () => React.useContext(context)
export default useStore

But we all know that hooks can only be used in function components or hooks, not in ts/js code, but I have a requirement here. I want to make a post-processor every time an interface request is sent for Obtain interface usage and remaining times, and update in real time on the interface.

This requires us to update the interface data in the mobx in the js/ts requested by the interface to achieve responsive updates. At this time, useContext cannot be used, because it can only be used in function components or hooks. At this time, we need to use the rootStore object alone, then use the userInfo store in this object, and then call the method of modifying the data in it:

import { rootStore } from '@/store'


.....



// 导入或创建你的 MobX store 对象
const { userInfo } = rootStore



....


// 重新获取API接口速率
export const getApiLimit = () => {
    let payload = {
        method: 'GET' as HttpVerb,
        headers: {
            Authorization: `Bearer ${localStorage.getItem('token') || ''}`,
            'User-Agent': 'PostmanRuntime/7.32.3',
        },
    }
    fetch('https://api.github.com/rate_limit', payload)
        .then(({ status, data }) => {
            if (status >= 200 && status < 500) {
                console.log('apilimit---', data)
                userInfo.setApiLimit((data as any).rate)
            }
        })
        .catch((err) => {
            console.error('apilimiterr-------', err)
        })
}

Introduce this userInfo store: 

Call the function that modifies the data:

Then in the component that needs to use the data, turn the component into a component that can listen:

Finally, it can be found on the interface that the data can be synchronously responsive:

Guess you like

Origin blog.csdn.net/weixin_44786530/article/details/132467766