1

I want to print this data on my mobile screen but it shows me nothing when I write the code from this response:

my response from api

This is my code:

    const [data, setData] = useState('')
      useEffect(() => {
        getData()
    
      }, [])
 const getData = async () => {

    fetch(`${urldemo}blog/${slug}?token=${user_token}`, {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    })

      .then((response) => response.json())
      .then((responseJson) => {
        setLoading(false);
        setData([...data, ...responseJson.result]);  
        console.log("log for Exploreblogs =====>", responseJson.result)

      })
      .catch((error) => {
        console.error(error);
      });
  }

This is my return code where I am stuck:

         const renderItem = ({ item }) => {
    
        return (
          <ScrollView style={[styles.footer, {
            backgroundColor: "white"
            // colors.background
          }]}>
    
            <Card style={{ marginHorizontal: 20, }}>
              <Card.Cover style={{ marginVertical: 10, borderRadius: 10, height: 200, }}
                source={require('../../../assets/imagehere.png')} />
    
              <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
    
                <Image
                  source={require('../../../assets/news9.png')} />
    
                <Text style={{ textAlign: 'right', color: "orange" }}>
                  {item.short_description}
    
                </Text>
              </View>
              <Text style={{ textAlign: 'center', color: "black", fontSize: 24 }}>
                {item.description}
    
              </Text>
    
              <View style={{
                justifyContent: "space-between",
                flexDirection: "row",
                marginHorizontal: 10
              }}>
                <View style={{ flexDirection: "row" }}>
    
                  <Text style={{ color: "green" }}>4hrs ago</Text>
                  <Text style={{ color: "green" }}> ~ 5 min read</Text>
                </View>
    
                <View style={{ flexDirection: "row" }}>
                  <Image
                    source={require('../../../assets/comment.png')} />
                  <Image style={{ marginHorizontal: 10 }}
                    source={require('../../../assets/shae.png')} />
                  <Image
                    source={require('../../../assets/saved.png')} />
                </View>
              </View>
            </Card>
    
            {/* <Text style={{
              textAlign: 'left', color: "grey", fontSize: 16,
              marginHorizontal: 20, marginVertical: 20
            }}>
             {item.title}
            </Text> */}
    
            <Image style={{ marginHorizontal: 20, width: "90%", borderRadius: 10 }}
              source={require('../../../assets/exnews.png')} />
            <Text style={{ marginHorizontal: 20 }}>{item.description}</Text>
    
    
            <Text style={{
              textAlign: 'left', color: "grey", fontSize: 16,
              marginHorizontal: 20, marginVertical: 20
            }}>
              {item.short_description}
            </Text>
    
    
    
          </ScrollView>
        );
      }
    return (
        <TouchableOpacity >
          {/* <BlogsHeader />
          
          */}
    
          <Animatable.View
    
            animation="zoomIn" >
    
            <View style={{
              flexDirection: 'row',
              flexWrap: 'wrap',
              justifyContent: 'space-between',
              backgroundColor: 'white',
              height: 45,
            }}>
              <TouchableOpacity onPress={() => navigation.navigate('Blogs')}>
                <Image style={{
                  color: 'black',
                  marginTop: 15,
                  tintColor: 'orange'
                }}
                  source={require('../../../assets/backicon.png')}
                />
              </TouchableOpacity>
    
              <Text style={{
                fontSize: 15,
                color: '#FF7F23',
                textAlign: "center",
                marginTop: 15,
              }}
              > Blogs</Text>
    
              <Image style={{ color: 'black', marginTop: 15, alignSelf: 'center', }}
                source={require('../../../assets/avatar.png')}
              />
            </View>
    
            {isLoading ? <ActivityIndicator size="large" color="#FF8025" /> : (
              <FlatList
                style={styles.container}
                data={data}
                renderItem={renderItem}
                keyExtractor={(item, index) => index.toString()}
    
              />
            )
            }
          </Animatable.View>
        </TouchableOpacity>
      )

I have used Flatlist for Item.
I just want to print my response data on my mobile screen but it didn't work for me

I get following error message in the console output:

[TypeError: Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a Symbol.iterator method.]

Stephan Bauer
  • 9,120
  • 5
  • 36
  • 58
ABDULLAH
  • 550
  • 3
  • 13
  • Do you have console errors? If you have defined `getData()` after the call in `useEffect` it should be undefined. – Code Spirit May 24 '22 at 10:06
  • @jonrsharpe yes this is the error in console [TypeError: Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.] – ABDULLAH May 24 '22 at 10:07

1 Answers1

0

The problem is with this line:

setData([...data, ...responseJson.result]);  

I'm assuming responseJson.result is an object, in which case this won't work since you can't spread an object into an array, at least in the way you intend.

This should work for you though:

const [data, setData] = useState({}) // Use object instead

// Other stuff

setData({...data, ...responseJson.result}); // Spread to object instead.

Alternatively, consider checking out these solutions e.g. for...of or Object.keys()/entries()/....

Otherwise, you would need to post the value responseJson.result for more troubleshooting.

  • it didn't work for me . i have response from API but it is not print on mobile screen – ABDULLAH May 24 '22 at 12:24
  • Any errors? Also, I'd have to see more of the return code, since you use `item` there so I can't tell how you're even using `data`. – Piotr Płaczek May 24 '22 at 14:57
  • Placzek I updated the above code – ABDULLAH May 25 '22 at 06:27
  • @ABDULLAH Can you show the error you get after changing the code (If there is any)? Also, please show a response from the api so we can get some kind of idea of what it looks like. – Piotr Płaczek May 25 '22 at 08:33
  • you can see the error in the above picture. Errors are below in the picture – ABDULLAH May 25 '22 at 08:37
  • @ABDULLAH see [this snack](https://snack.expo.dev/@razermoon/bruh) for a working example. The main thing I did (apart from my first fix) is change to this `data={[data]}`. – Piotr Płaczek May 25 '22 at 09:44