Reader small image

You're reading from  React and React Native - Fifth Edition

Product typeBook
Published inApr 2024
Reading LevelBeginner
PublisherPackt
ISBN-139781805127307
Edition5th Edition
Languages
Tools
Right arrow
Authors (2):
Mikhail Sakhniuk
Mikhail Sakhniuk
author image
Mikhail Sakhniuk

Mikhail Sakhniuk is Software Engineer with high proficiency in JavaScript, React and React Native. He has more than 5 years of experience in developing web and mobile applications. He has worked for startups, fintech companies, and product companies with more than 20 million users. Currently, Mikhail is working at Miro as a Frontend Engineer. In addition, he owns and maintains a few open-source projects. He also shares his experience and knowledge through books and articles.
Read more about Mikhail Sakhniuk

Adam Boduch
Adam Boduch
author image
Adam Boduch

Adam Boduch has been involved in large-scale JavaScript development for nearly 15 years. Before moving to the frontend, he worked on several large-scale cloud computing products using Python and Linux. No stranger to complexity, Adam has practical experience with real-world software systems and the scaling challenges they pose.
Read more about Adam Boduch

View More author details
Right arrow

Going Offline

Users expect applications to operate seamlessly with unreliable network connections. If your mobile application can’t cope with transient network issues, your users will use a different app. When there’s no network, you have to persist data locally on the device. Alternatively, perhaps your app doesn’t even require network access, in which case you’ll still need to store data locally.

In this chapter, you’ll learn how to do those three things with React Native. First, you’ll learn how to detect the state of the network connection. Second, you’ll learn how to store data locally. Lastly, you’ll learn how to synchronize local data that’s been stored due to network problems once it comes back online.

In this chapter, we’ll cover the following topics:

  • Detecting the state of the network
  • Storing application data
  • Synchronizing application data

Technical requirements

You can find the code files for this chapter on GitHub at https://github.com/PacktPublishing/React-and-React-Native-5E/tree/main/Chapter28.

Detecting the state of the network

If your code tries to make a request over the network while disconnected using fetch(), for example an error will occur. You probably have error-handling code in place for these scenarios already, since the server could return some other type of error.

However, in the case of connectivity trouble, you might want to detect this issue before the user attempts to make network requests.

There are two potential reasons for proactively detecting the network state. The first one is to prevent the user from performing any network requests until you’ve detected that the app is back online. To do that, you can display a friendly message to the user stating that, since the network is disconnected, they can’t do anything. The other possible benefit of early network state detection is that you can prepare to perform actions offline and sync the app state when the network is connected again.

Let’s look at some code that uses the...

Storing application data

To store data on the device, there is a special cross-platform solution called AsyncStorage API. It works the same on both the iOS and Android platforms. You would use this API for applications that don’t require any network connectivity in the first place or to store data that will eventually be synchronized using an API endpoint once a network becomes available.

To install the async-storage package, run the following command:

npx expo install @react-native-async-storage/async-storage

Let’s look at some code that allows the user to enter a key and a value and then stores them:

export default function App() {
  const [key, setKey] = useState("");
  const [value, setValue] = useState("");
  const [source, setSource] = useState<KeyValuePair[]>([]);

The key, value, and source values will handle our state. To save it in AsyncStorage, we need to define functions:

  function setItem() {
    return...

Synchronizing application data

So far in this chapter, you’ve learned how to detect the state of a network connection and how to store data locally in a React Native application. Now, it’s time to combine these two concepts and implement an app that can detect network outages and continue to function.

The basic idea is to only make network requests when you know for sure that the device is online. If you know that it isn’t, you can store any changes in the state locally. Then, when you’re back online, you can synchronize those stored changes with the remote API.

Let’s implement a simplified React Native app that does this. The first step is to implement an abstraction that sits between the React components and the network calls that store data. We’ll call this module store.ts:

export function set(key: Key, value: boolean) {
  return new Promise((resolve, reject) => {
    if (connected) {
      fakeNetworkData[key] = value;
...

Summary

This chapter introduced us to storing data offline in React Native applications. The main reason we would want to store data locally is when the device goes offline and our app can’t communicate with a remote API. However, not all applications require API calls, and AsyncStorage can be used as a general-purpose storage mechanism. We just need to implement the appropriate abstractions around it.

We also learned how to detect changes in the network state of React Native apps. It’s important to know when the device has gone offline so that our storage layer doesn’t make pointless attempts at network calls. Instead, we can let the user know that the device is offline and then synchronize the application state when a connection is available.

In the next chapter, we’ll learn how to import and use UI components from the NativeBase library.

Join us on Discord!

Read this book alongside other users and the authors themselves. Ask questions, provide solutions to other readers, chat with the authors, and more. Scan the QR code or visit the link to join the community.

https://packt.link/ReactAndReactNative5e

lock icon
The rest of the chapter is locked
You have been reading a chapter from
React and React Native - Fifth Edition
Published in: Apr 2024Publisher: PacktISBN-13: 9781805127307
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at AU $19.99/month. Cancel anytime

Authors (2)

author image
Mikhail Sakhniuk

Mikhail Sakhniuk is Software Engineer with high proficiency in JavaScript, React and React Native. He has more than 5 years of experience in developing web and mobile applications. He has worked for startups, fintech companies, and product companies with more than 20 million users. Currently, Mikhail is working at Miro as a Frontend Engineer. In addition, he owns and maintains a few open-source projects. He also shares his experience and knowledge through books and articles.
Read more about Mikhail Sakhniuk

author image
Adam Boduch

Adam Boduch has been involved in large-scale JavaScript development for nearly 15 years. Before moving to the frontend, he worked on several large-scale cloud computing products using Python and Linux. No stranger to complexity, Adam has practical experience with real-world software systems and the scaling challenges they pose.
Read more about Adam Boduch