Raynier lara
Raynier lara

Reputation: 3

React Native Fetch API json returning old data

I am new to react native and I have a problem receiving an image with a link from a json api.

I have an app and in a section of the screen I am putting an image that can vary depending on the name of the image that I put in the json. It is something quite simple, but for the moment it is what I need for the app.

The problem is the following: when I change the url from where the application will take the image and the link that that image will redirect to the user, the app continues presenting the old link and the old image.

I have changed several times and also read that putting "'Cache-Control: no-cache'" this would solve, but it has not been my case.

I would greatly appreciate your help please and thank you in advance.

Here is my code:

JSON

{
"Home": [
    { 
        "id": "1",
        "LinkHome":"https://www.instagram.com/masterchefrdominicana/?hl=es",
        "URLHome":"https://teleantillas.com.do/wp-content/uploads/telestream/banners/mchef.jpeg"
    }
]}

MY CODE:

    export default class GetDatajson extends Component{
  constructor(props) {
    super(props);

    this.state = {
      data: [],
      isLoading: true
    };
  }
  async fetchData(){
    try{
      const response = await
    fetch
      ('https://teleantillas.com.do/wp-content/uploads/telestream/json/PublicidadTeleStream.json',
      {
        method: 'GET',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
          'Cache-Control': 'no-cache'
        }
      })
        const json = await response.json();
        this.setState({ data: json.Home });
        }catch(error) { console.error(error);}
        finally{
          this.setState({ isLoading: false });
        }
  }

  componentDidMount() {
      this.fetchData();
    }
    render(){
      const { data, isLoading } = this.state;
      return(
        <View style ={styles.jsonHome}>
          {isLoading ? <ActivityIndicator/> : (
          <FlatList
            data={data}
            keyExtractor={({ id }, index) => id}
            renderItem={({ item }) => (
              <TouchableOpacity style={styles.i8mgcontainer} onPress={()=>
                Linking.openURL(item.LinkHome)
              }>
                <Image
                  style={styles.imgad}
                  source={{uri: item.URLHome}}
                />     
              </TouchableOpacity>
            )}
          />
          )}
      </View>
      )
      }
  }

Upvotes: 0

Views: 457

Answers (1)

mfarahy
mfarahy

Reputation: 88

FlatList uses ID as cache key so if you change your ID when you want receive new data and url, it would be resolved.

https://reactnative.dev/docs/flatlist#keyextractor

Upvotes: 1

Related Questions