Home > OS >  Fetch data from API in React Native
Fetch data from API in React Native

Time:11-11

I want to know how I can get data from an API, create all react elements and only when it's all finished make the render on the app. Actually I use the hooks to do it but the problem is that in first start the app is rendered without API data, before, because I use hooks in the code to store and use API data, the app re-renders quickly with all data. (I learned that happens because when I change hooks value with the function the code continue and at the and restart without previous inputs)

I hope I was clear, my English is not too good

Code: https://nekobin.com/dolusaxawi

CodePudding user response:

This should make the work:

import React, {Button} from 'react';

const RequestTest = () => {
    const request = fetch('https://examples.com/data.json', {
        method: 'POST',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            firstParam: 'yourValue'
        })
    });

    return (
        <Button onClick={request}>
            Make simple request
        </Button>
    );
}

CodePudding user response:

The hook useEffect is called only after the component has been rendered so it is why data is empty at the beggining.

  • Related