I have a class like this creating a state graph
// Graph
const fetchTransactionsActor = fromPromise(async () => {
console.log('fetchTransactions service called');
const response = await fetch('/transaction');
if (!response.ok) {
throw new Error('Failed to fetch transactions');
}
return await response.json();
});
const transactionMachine = setup({
actors: {
fetchTransactionsActor,
updateTransactionActor,
deleteTransactionActor
}
}).createMachine({
id: 'transactions',
initial: 'idle',
entry: {
type: 'FETCH'
},
context: {
transactions: [],
error: null
},
states: {
idle: {
on: {
FETCH: 'loading',
UPDATE: 'updating',
DELETE: 'deleting'
}
},
loading: {
invoke: {
src: 'fetchTransactionsActor',
onDone: {
target: 'success',
actions: assign(
({event}) => ({
transactions: event.output,
})
)
},
onError: {
target: 'failure',
actions: assign(({event}) => ({
error: event.error
}))
}
}
},
updating: {
invoke: {
src: 'updateTransactionActor',
onDone: {
target: 'success'
},
onError: {
target: 'failure',
actions: assign(({event}) => ({
error: event.error
}))
}
}
},
deleting: {
invoke: {
src: 'deleteTransactionActor',
input: ({event}) => event.data,
onDone: {
target: 'success'
},
onError: {
target: 'failure',
actions: assign(({event}) => ({
error: event.error
}))
}
}
},
success: {
// on: {
// REFRESH: 'loading'
// }
},
failure: {
// on: {
// RETRY: 'loading'
// }
}
}
});
// Provider
import React, {createContext, useContext, useEffect} from 'react';
import {useMachine} from '@xstate/react';
import transactionMachine from './transactionMachine';
const TransactionContext = createContext();
export const TransactionProvider = ({children}) => {
const [state, send] = useMachine(transactionMachine);
useEffect(() => {
(async () =>
await send(
{type: 'FETCH'}
)
)();
}, [send]);
return (
<TransactionContext.Provider value={{state, send}}>
{children}
</TransactionContext.Provider>
);
};
export const useTransactionContext = () => {
return useContext(TransactionContext);
};
This works great but now I would like to call the same (for now) FETCH function from another component so I wrap my app in <TransactionProvider> and I try the following…
const TransactionItem = ({txn: initialTxn, refreshTransactions}) => {
const { send } = useTransactionContext();
const [txn, setTxn] = useState(initialTxn);
...
const onSave = async () => {
console.log("Trying to send the information")
send({ type: 'FETCH' });
};
I see the “Trying to send the information” but never “fetchTransactions service called”
What am I missing why isn’t the actor getting called and why am I not seeing the info in the console?