簡體   English   中英

有沒有辦法使用從 Firebase 返回的 promise 初始化 Xstate state 機器?

[英]Is there a way to initialize an Xstate state machine using a promise returned from Firebase?

我正在嘗試使用 Firebase 來堅持 state。 我目前正在使用“saveState”function,它可以正常工作並將最新的 state 正確保存到 Firebase。

現在我希望能夠根據 Firebase 中最近保存的 state 來初始化 state 機器。 在下面的代碼中,我嘗試使用我的“loadState”function 為 Xstate 提供配置 object。 它當前返回一個 promise,其中包含正確的 state 配置。

這是我的“保存狀態”代碼:

 //This function works fine.
 function saveState(current, id){
        let transactionJSON = serialize(current);
        transactionJSON['createdOn'] = new Date();
        return firebase.saveTransactionState({transactionJSON, transactionId:id});
    }

這是我的“loadState”function,它從 Firebase 返回 promise,其中包含正確的配置信息。

function loadState(id){
        return firebase.getTransactionState({transactionId:id}).then(function(querySnapshot) {
            return querySnapshot.docs.map(doc => deserialize({...doc.data()})  );
        });
    };

現在我的問題是嘗試使用上面的'loadState' function 加載 Xstate。 在這里,我嘗試使用 useMachine React 鈎子:

const [current, send] = useMachine(transactionMachine,{
        state: () => loadState(id), //Trying to do something like this, but it doesn't seem to work.
        actions:{
            save: () => saveState(current, id),
        },
    });

我最終得到錯誤:“TypeError:無法讀取未定義的屬性'數據'”,我認為這是因為 promise 尚未解決導致嘗試讀取未定義的值。

這甚至可能嗎,還是我做錯了?

我對這一切都很陌生,任何指導將不勝感激。 謝謝你。

我想您可以使用useEffect在獲取后更新您的 state 機器。

在 state 機器中調用 fetch 怎么樣?


import { Machine, assign } from 'xstate';


const yourMachine = Machine({

    id: 'yourStateMachine',
    initial: 'fetching',
    context: {
        values: {
            id: '', // likely need a state to initialize this value before fetching
            apiDat: {}
        },
    },
    states: {

        fetching: {
            invoke: {
                src: ({values}) => firebase
                    .getTransactionState({ transactionId: values.id })
                    .then(function(querySnapshot) {
                        return querySnapshot.docs.map(
                            doc => deserialize({...doc.data()})  
                        );
                    }),
                onDone: { target: 'resolving', actions: 'cacheApiDat' },
                onError: { target: 'error.fetchFailed' },
            }
        },

        resolving: {
            initial: 'delay',
            states: {
                delay: { 
                    after: { 
                        750: 'resolve' 
                    }, 
                },
                resolve: {
                    always: [
                        { cond: 'isSuccess', target: '#yourStateMachine.idle' },
                        { cond: 'isUnauthorized', target: '#yourStateMachine.error.auth' },
                    ],
                }
            },
        },

        error: {
            states: {
                fetchFailed: {
                    type: 'final',
                },
                auth: {
                    type: 'final',
                }
            }
        },

        idle: {

        },

    }



},{

    actions: {

         cacheApiDat: assign({ values: ({values}, event) => ({
                   ...values,
                   apiDat: event.data, // save whatever values you need here
              }),
         }),

    },

    guards: {
        // this requires a definition based on firebase's returned api call on a success
        isSuccess: ({values}) => typeof values.apiDat.data !== 'undefined',
        // this requires a definition based on firebase's returned api call when the call is unauthorized
        isUnauthorized: ({values}) => typeof values.apiDat.detail !== 'undefined' && values.apiDat.detail === 'invalid_auth',
    }

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM