lundi 20 septembre 2021

using Onclick, fetch api data in react native

I am new to React Native. I am facing an issue with this view. Basically it is something like this when you click a button it generates any random number, now this random number becomes an id and it goes to at the end of the API url, And using this new API - with ID at the end of it. - data gets fetched. Now i've divided this task in two parts generating random number code (i.e. snippet 1) and fetching data from api ( i.e. snippet 2). As of now, I don't know how to combine them because i am new to react native so a little help here would be appreciated from anyone.

Snipppet 1

import { StyleSheet, View, Button, Text } from 'react-native';
export default class MyProject extends Component {
  constructor(){
    super();
    this.state={
      // This is our Default number value
      NumberHolder : 0
    }
  }
GenerateRandomNumber=()=>
{
var RandomNumber = Math.floor(Math.random() * 5000) + 1 ;
this.setState({
  NumberHolder : RandomNumber
})
}
  render() {
    return (  
      <View style={styles.MainContainer} >
       <Text style=>{this.state.NumberHolder}</Text>
       <Button title="Generate Random Number" onPress={this.GenerateRandomNumber} />      
      </View>
    );
  }
}
const styles = StyleSheet.create(
{
  MainContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  }
});

Snippet 2

import React, { useState } from "react";
import { Box, FlatList, Center, NativeBaseProvider, Button } from "native-base";
import { StyleSheet, View, ActivityIndicator, Text, TouchableOpacity, Image } from 'react-native';

export default function MyFUnction() {
  
  const [data, setData] = useState(null);
  const [visible, setVisible] = useState(true);

  const fetchData = async () => {
    const resp = await fetch("https://jsonplaceholder.typicode.com/photos/7");
    const data = await resp.json();
    setData(data);
    setVisible(false);
  };

  const renderItem = ({ item }) => {
    return (
      <TouchableOpacity style={styles.list}>
        <Text>{item.title}</Text>
      </TouchableOpacity>
    );
  };

  return (
    <NativeBaseProvider>
      <Center flex={1}>
        {visible && <Button onPress={() => fetchData()}>Press</Button>}
        {data && (
          <FlatList
            data={data}
            renderItem={(item) => this.renderItem(item)}
            keyExtractor={(item) => item.id.toString()}
          />
        )}
      </Center>
    </NativeBaseProvider>
  );
}

const styles = StyleSheet.create({
  list: {
    paddingVertical: 4,
    margin: 5,
    backgroundColor: '#fff',
  },
});

Thanks in advance!!




Aucun commentaire:

Enregistrer un commentaire