Data Driven React Native Apps

React Native HTTP Request to Populate a List

Jake Cyr
2 min readOct 6, 2020

Let’s create a simple app screen with a list populate through an HTTP request using fetch.

Photo by Tudor Baciu on Unsplash

Making HTTP requests from React Native is pretty easy given the built in fetch API.

Below are the steps you can follow to make an API request and populate a list:

  1. In the component you want to load data for, add a useEffect block that calls your API (modify the Todo type to your data model)
const [todos, setTodos] = useState<Todo[]>([]);
useEffect(() => { fetch('http://localhost:8080/api/todo') .then((res: Response): Promise<Todo[]> => res.json()) .then((todos: Todo[]) => setTodos(todos)) .catch((error) => console.error('Error loading todos', error));}, []);

2. Add a FlatList to your JSX return value and pass in the todos list:

<FlatList    data={todos}    renderItem={({ item }) => (        <View>            <Text>{item.todo}</Text>        </View>    )}/>

And that’s it!

Possible Improvements

  • Move fetch calls into separate files grouped by type (ex. Todo related requests, user related requests, etc.)
  • Show loading indicator when waiting for API to respond (could use separate state variable that is set to true in the beginning of the useEffect block and set to false in a finally block after the .catch)
  • Show error message if there is an error when requesting data from the API (could use separate state variable error that is set in the catch block. Don’t forget to clear out the error on retry)

Feel free to leave a response if you have any questions and click the 👏 button if you like the article. Don’t forget to follow me so you don’t miss out on future React Native articles!

Checkout my video on creating a complete React Native app in 30 minutes:

Other React Native Articles

--

--

Jake Cyr
Jake Cyr

Written by Jake Cyr

Proficient in AI and cloud tech, advancing systems development with a commitment to continual growth.

No responses yet