اذهب إلى المحتوى
  • 0

كيف أحول هذا ال Action من ال Fetch الى Axios فى هذا الكود ؟

Ahmed Sawy

السؤال

السلام عليكم .. 

أريد ان اكتب هذا الاكشن ولكن باستخدام Axios وليس باستخدام ال Fetch .. ما هى التغييرات التى يجب ان أجريها هنا ؟؟

export const fetchProducts = () => {
  return async (dispatch) => {
    try {
      const response = await fetch(
        "https://rn-shopping-app-69186.firebaseio.com/products.json"
      );

      if (!response.ok) {
        throw new Error("Error - something went wrong");
      }

      const resData = await response.json();
      const loadedProducts = [];
      for (const key in resData) {
        loadedProducts.push(
          new Product(
            key,
            resData[key].title,
            resData[key].imageUrl,
            resData[key].description,
            resData[key].price
          )
        );
      }
      dispatch({
        type: SET_PRODUCTS,
        products: loadedProducts,
      });
    } catch (error) {
      throw error;
    }
  };
};

 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

Recommended Posts

  • 1

اولا انت تحتاج لجلب مكتبة axios عن طريق

npm i --save axios

او 

yarn add axios

ثم قم بتغيير الكود كالتالي

export const fetchProducts = () => {
  return async (dispatch) => {
    try {
      const response = await axios.get("https://rn-shopping-app-69186.firebaseio.com/products.json");
      
      if (!response.status === 200) {
        throw new Error("Error - something went wrong");
      }

      const resData = await response.data; 
      
      const loadedProducts = [];
      for (const key in resData) {
        loadedProducts.push(
          new Product(
            key,
            resData[key].title,
            resData[key].imageUrl,
            resData[key].description,
            resData[key].price
          )
        );
      }
      dispatch({
        type: SET_PRODUCTS,
        products: loadedProducts,
      });
    } catch (error) {
      throw error;
    }
  };
};

وهذه بعض الاختلافات بين fetch و axios

  • fetch يرجع body اما axios يرجع data
  • في ال post request يجب ان ننادي JSON.stringify على ال body فيما يخص fetch
  • في fetch طلب الجلب يكون ok عندما تحتوي الاجابة على ok اما بالنسبة ل axios فيجب ان يحتوي طلب الجلب status =200 و statusText يكون ok
  • للحصول على ال json في fetch ننادي الدالة json على الاجابة اما بانسبة ل axios ندخل لل data مباشرة 
رابط هذا التعليق
شارك على الشبكات الإجتماعية

  • 1

لن يتغير شكل الأكواد كثيرًا، بعد التعديل سيصبح مثل هذا

export const fetchProducts = () => {
  return async (dispatch) => {
    try {
      const response = await axios.get("https://rn-shopping-app-69186.firebaseio.com/products.json");
      
      if (!response.status === 200) { // response.ok ليس 
        throw new Error("Error - something went wrong");
      }

      const resData = await response.data; //  response.json  بدلًا من response.data 
      
      const loadedProducts = [];
      for (const key in resData) {
        loadedProducts.push(
          new Product(
            key,
            resData[key].title,
            resData[key].imageUrl,
            resData[key].description,
            resData[key].price
          )
        );
      }
      dispatch({
        type: SET_PRODUCTS,
        products: loadedProducts,
      });
    } catch (error) {
      throw error;
    }
  };
};

لاحظ المثال التالي لاستخدام Axios مع ال Action :

export const fetchData = () => {
    return (dispatch) => {
        return axios.get(apiUrl)
            .then(response => {
                return response.data
            })
            .then(data => {
                dispatch({
                    type: ADD_FETCHED_DATA,
                    payload: data
                })
            })
            .catch(error => {
                throw (error);
            });
    };
};

 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...