Answer the question
In order to leave comments, you need to log in
How to update data in redux c async function?
I have a walletReducer that can change depending on the user's actions, for example, when I change my wallet, I have to update its address and balance on the site. I receive this data in an asynchronous function and now the update fails.
const walletDefaultState = {
web3: {},
account: "",
balance: "",
};
const CONNECT_BY_METAMASK = "CONNECT_BY_METAMASK";
const WALLET_CONNECT = "WALLET_CONNECT";
export const walletReducer = (state = walletDefaultState, action) => {
switch (action.type) {
case CONNECT_BY_METAMASK:
return { ...state, ...action.payload };
case WALLET_CONNECT:
return { ...state, cash: state.cash - action.payload };
default:
return state;
}
};
export const connectByMetaMaskAction = (payload) => ({
type: CONNECT_BY_METAMASK,
payload,
});
import Web3 from "web3";
import { connectByMetaMaskAction } from "../../store/walletReducer";
export function createWeb3Listeners() {
if (window.ethereum) {
window.ethereum.on("accountsChanged", async () => {
console.log("accountsChanged");
const web3 = new Web3(window.ethereum);
let accounts = await web3.eth.getAccounts();
let balance = await web3.eth.getBalance(accounts[0]);
dispatch(connectByMetaMaskAction({ web3, accounts, balance }));
});
window.ethereum.on("chainChanged", () => {
console.log("chainChanged");
});
window.ethereum.on("disconnect", () => {
console.log("disconnect");
});
}
}
Answer the question
In order to leave comments, you need to log in
For asynchronous logic, you need to include the redux-thunk library or similar,
because actions in Redux are synchronous by default
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question