skip to Main Content

I encountered a problem while trying to fetch data from an API URL, the problem is that the data are not returning by the category title in the SectionList instead I have the data returning under the title [object Object] instead of the renderSectionHeader.

My issue reproduction Snack Expo:
https://snack.expo.dev/@fyardlest/resto-app?platform=android

enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    I also modify the way I fetch the data and it works too. here is what I have done by setting up the category:

    const fetchData = async () => {
    try {
      const response = await fetch(API_URL);
    
      if (!response.ok) {
        throw new Error('Failed to fetch data');
      }
    
      const data = await response.json();
    
      // here is the way I retrieve the category title
    
      menuItems = data.menu.map((item) => ({
        ...item,
        category: item.category.title
      }))
    
      return menuItems
    } catch (error) {
      console.error('Error fetching data:', error);
      return [];
    }
    
    };
    

  2. Your data type schema isn’t matched to the SectionList requirement. Please take a look at the given link. Your data schema is like the following:

    [
      { category: {title: 'Appetizers'}, id: 1, price: "10", title: "Spinach Artichoke Dip" },
      ~~~
      ~~~
    ]
    

    But the SectionList component expects the following:

    [
      {
        title: 'Main dishes',
        data: ['Pizza', 'Burger', 'Risotto'],
      },
    ]
    

    A SectionList except the first array level needs one level deeper though. So I think you should use FlatList.


    However, the main issue comes from your saveMenuItems function:

    export function saveMenuItems(menuItems) {
      db.transaction((tx) => {
        const values = menuItems
          .map(
            (item) =>
              `('${item.id}', '${item.title}', '${item.price}', '${item.category}')`
          )
          .join(', ');
    
        tx.executeSql(
          `insert into menuitems (uuid, title, price, category) values ${values};`
        );
      });
    }
    
    

    This function makes the category as [object Object] because you used ${item.category} which the item.categorty is an object like this: { title: 'something' }. And then inside getSectionListData the issue appears itself and makes another issue.

    I think you should use ${item.category.title} in the saveMenuItems function.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search