Search code examples
react-nativefetch

React Native API call


How do I display results from the API call in code lower in the page?

The {data.payrollid} after Complete is not showing any value. ie: the text only shows 'Complete' with no value after it.

My returned JSON looks like this...

{"status_code":200,"payrollid":10,"message":"Success"}

When I console.log(data) I can see that the fetch worked and I can see my JSON array.

Below is my React Native code

 const [isLoading, setLoading] = useState(true);
    const [data, setData] = useState([]);

    useEffect(() => {
        fetch('https://www.mywebsite.ca/api/test.php')
            .then((response) => response.json())
            .then((data) => console.log(data))
            .catch((error) => console.error(error))
            .finally(() => setLoading(false));
    }, []);

  return (
      <>
      <View>
          {isLoading ? <Text>Loading...</Text> : <Text>Complete {data.payrollid}</Text> }
      </View>
    <View style={styles.container}>
      <Text>This is my new app.</Text>
      <Text>Some text</Text>
      <StatusBar style="auto" />
    </View>
      </>
  );

Solution

  • You need to save your data in your data state.

    const [data, setData] = useState({});
    
    useEffect(() => {
        fetch('https://www.mywebsite.ca/api/test.php')
            .then((response) => response.json())
            .then((data) => setData(data))
            .catch((error) => console.error(error))
            .finally(() => setLoading(false));
    }, []);
    

    And since your getting an object switch your original state to an object.