Data Driven React Native Apps
Let’s create a simple app screen with a list populate through an HTTP request using fetch
.
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:
- In the component you want to load data for, add a
useEffect
block that calls your API (modify theTodo
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 theuseEffect
block and set tofalse
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 thecatch
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: