How can I use React Hook in actions? #1689
-
I want to use React Hook in actions. But React complains that the hook can only be used in a React component. Axios (React Hook):
Store (mobx-state-tree):
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Hi @thanksyouall! Just like you said hooks is a React-specific feature that can only be used in function React components. Maybe what you are trying to do can be achieved with dependency injection instead? Example // hooks/useAxios.js
import { createContext, useContext } from "react";
const AxiosContext = createContext();
export const AxiosProvider = AxiosContext.AxiosProvider;
export const useAxios = () => useContext(AxiosContext);
// hooks/useStore.js
import { createContext, useContext } from "react";
const StoreContext = createContext();
export const StoreProvider = StoreContext.Provider;
export const useStore = () => useContext(StoreContext);
// index.js
import React from "react";
import ReactDOM from "react-dom";
import axios from "axios";
import { types, flow, getEnv } from "mobx-state-tree";
import { AxiosProvider, useAxios } from "./hooks/useAxios";
import { StoreProvider, useStore } from "./hooks/useStore";
const MyStore = types.model("MyStore", {}).actions((self) => {
// We use axios supplied to the model instance through the environment.
const { axios } = getEnv(self);
return {
getUser: flow(function* () {
try {
const response = yield axios.get("/user/");
// ...
} catch ({ response }) {
console.log("response", response);
}
})
};
});
const instance = axios.create({
baseURL: "http://localhost:8000"
});
// Here we pass the axios instance as "axios" to the environment.
const myStore = MyStore.create({}, { axios: instance });
function App() {
const store = useStore();
const axios = useAxios();
// ...
}
ReactDOM.render(
<AxiosProvider value={instance}>
<StoreProvider value={myStore}>
<App />
</StoreProvider>
</AxiosProvider>,
document.getElementById("root")
); |
Beta Was this translation helpful? Give feedback.
-
I found a solution. It turns out that you can add axios.interceptors anywhere. And it will work globally.
|
Beta Was this translation helpful? Give feedback.
I found a solution. It turns out that you can add axios.interceptors anywhere. And it will work globally.
So just call axios.interceptors in any React component. And now we can use our store in it.