تابستون داره تموم میشه ها، فرصت‌ها محدودن کلی آفر جذاب در کمپین تابستون🔥👇
۰ ثانیه
۰ دقیقه
۰ ساعت
۱ salar keshavarzi
پیاده سازی سرویس axois
جامعه ری اکت ایجاد شده در ۰۲ آذر ۱۴۰۲

با سلام. من سرویس axios رو در توابعی نوشتم که تمام درخواست‌ها رو هندل می‌کنه. بطور مثال در کد زیر درخواست get ارسال میشه. چطور می‌تونم هوک authDispatch رو صدا بزنم در صورتی که get تنها یک تابع ساده هس؟

const get = async (uri) => {
        const url = BaseUrl + uri
        try {
            const accessToken = localStorage.getItem('access_token');
            const response = await axios.get(url, {
                headers: { Authorization: `Bearer ${accessToken}` }
            });
            return response.data;
        } catch (error) {
            if (error.response && error.response.status == '401') {
                authDispatch({ type: actionTypes.LOGOUT });
                notify('Log in to your account', 'info')
            }
            else if (error.response && error.response.status == '403') {
                notify('Permission denied', 'error')
            }
            else if (error.response && error.response.status == '404') {
                notify('Not found', 'error')
            }
            else if (error.message === 'Network Error') {
                notify('Connection error', 'error');
            }
            throw error;
        }
    };

سلام،

یک راه حل این هست که authDispatch رو به عنوان یک پارامتر به تابع get بفرستید:

const get = async (uri, authDispatch) => {
 // ...
 if (error.response && error.response.status == '401') {
   authDispatch({type: actionTypes.LOGOUT});
 }
 // ...
}
get(uri, authDispatch);

 

راه حل دیگه استفاده از context هست. مثلا یک AuthContext درست کنید که authDispatch و state رو نگه داره. بعد در کامپوننت‌هایی که نیاز دارند به authDispatch، از اون context استفاده کنید:

const AuthContext = React.createContext();
function App() {
 const [state, dispatch] = useReducer(authReducer);
 return (
   <AuthContext.Provider value={{state, dispatch}}>
     <GetComponent />
   </AuthContext.Provider>
 ) 
}
function GetComponent() {
 const {dispatch} = useContext(AuthContext);
 const get = async () => {
   // can access dispatch here
 }
 return <button onClick={get}>Get</button> 
}

این طوری دیگه نیاز نیست authDispatch رو به عنوان پارامتر بفرستید و در هر جایی از اپلیکیشن بهش دسترسی دارید.

محسن موحد ۰۳ آذر ۱۴۰۲، ۲۳:۴۶