Reputation: 85
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>
</>
);
Upvotes: 1
Views: 639
Reputation: 7152
Your code should look something like this:
const [isLoading, setLoading] = useState(true);
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));
}, []);
return (
<>
<View>
{isLoading ? <Text>Loading...</Text> :
<Text>Complete{data.payrollid}.</Text>
}
</View>
<View style={styles.container}>
<Text>This is my new app.</Text>
<Text>Your Text</Text>
<StatusBar style="auto" />
</View>
</>
);
Upvotes: 2
Reputation: 126
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.
Upvotes: 1