Home > Software engineering >  How to set array value in react native mobx?
How to set array value in react native mobx?

Time:11-23

I have favoriteStore and I'm new to mobx and I want to set the array from the bookmarkapi to the petList array, but I'm getting an error.

ERROR;

[Unhandled promise rejection: TypeError: undefined is not an object (evaluating '_this2.userId')]

CODE;

import { observable, computed, action, makeObservable, configure } from "mobx";
import { bookmarkApi, petApi } from '../../constants/apiURL';
import AsyncStorage from '@react-native-async-storage/async-storage';

configure({
    enforceActions: "never",
})

class Favorites {
    userId = 0;
    petList = [];

    constructor() {
        makeObservable(this, {
            userId: observable,
            petList: observable,
            bookMarkList: action
        })
    }

    bookMarkList = async () => {
        const value = await AsyncStorage.getItem('userId')
        if (value != null) {
            this.userId = value;
            console.log(this.userId);
        }

        bookmarkApi.get('/').then(function (responseJson) {
            this.petList = responseJson.data.filter(data => data.userId == this.userId)
        })
    }
}

export const favoriteStore = new Favorites();

CodePudding user response:

Callback function lost context, just use arrow function for bookmarkApi.get callback.

  • Related