Home > Enterprise >  How to render an array of images in Typescript?
How to render an array of images in Typescript?

Time:01-06

I have an array of objects. Each object has two properties: The first one is a string and the second one is an array of urls. this is an example of the json that I am working with:

{
  data : [ {contentString : "eating sushi", ["url", "url", "url"] },... ]
}

I want to use a FlatList to render each url in an Image component. However, in visual studio code I find that the property source in the Image component is undelined and displays the following error:

Type '{ uri: IUrl; }' is not assignable to type 'ImageSourcePropType | undefined'.
      Types of property 'uri' are incompatible.
        Type 'IUrl' is not assignable to type 'string'.

As I understand, url is indeed a string because, as shown in the code below, the interface IUrl defines its data type as a string so I can not see why I am getting this error. This is my code:

const Dashboard : React.FC  <DashScreenProps>= (props)=>{
   
    
    //interfaces
    //As mentioned above url is a string
    interface IUrl{
        url : string
    }

    interface IPost{
        contentString : string
        urls : IUrl[]
    }
    
    
   

    //local state variables
    const [arrayOfPosts, setArrayOfPosts] = useState<IPost[]>([])

   

    
    const getPostsFromFollowingUsers = async():Promise<boolean>=>{
        try {
            const response = await fetch(REMOTE_SERVER `/userPost/getPostsFromFollowingUsers/${id}`)
            const parseResponse = await response.json()
            console.log('those are the posts', parseResponse)
            setArrayOfPosts(parseResponse.data)
            
        } catch (error) {
            console.log(error)
            
        }    
        
    }

    
    useEffect(()=>{
        getPostsFromFollowingUsers()
    },[]) 
    return(
            <View>
                
                {arrayOfPosts.map(post=>{
                    //{contentString, urls}
                    return(
                        <FlatList
                        data = {post.urls}
                        renderItem={({item}) => {
                            return (
                                <Image source={{ uri: item }} style={{ width: 50, height: 50 }} />
                            )
                        }}  
                        />
                    )
                })}
                 
                
            </View>
    )
}

export default Dashboard

CodePudding user response:

Try to change your IPost interface declaration:

interface IPost{
    contentString : string
    urls : string[]
}

CodePudding user response:

You are fetching the wrong key data post.urls urls not exist in the given data also the data is an object type not an array in the .map only runs in case of an array

{
  data : [ {contentString : "eating sushi", ["url", "url", "url"] },... ]
}

Use this data then everything will be working fine

[
    {
      contentString: "eating sushi",
      url: [
        "https://cdn.pixabay.com/photo/2014/06/03/19/38/board-361516__340.jpg",
        "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQbJVpOdtk96FIiNKr9o2eVdz6pebpXb2n3UO6MjRDGABy-1EoDIjhwog9ACA7ez0RYH7Q&usqp=CAU",
        "https://cdn.xxl.thumbs.canstockphoto.com/test-concept-picture_csp17279717.jpg"
      ]
    }
  ]

or Try to change your IPost interface declaration:

interface IPost{
    contentString : string
    urls : string[] // wrong type here
}
  • Related