Guide To Deleting User Data in React Native

Following on from my last post, let’s dive into how we can delete expenses in our React Native app as well as exploring how to navigate between different screens, pass data and update the app’s state and the backend database. Let’s begin!

Navigate between screens and Pass Data

When passing data between screens, the navigation hook in React provides an easy way to achieve this! In our app we want to pass the id of the expense to be deleted using the following code:


function handlePress() {

      navigation.navigate("ManageExpenses", {

        id: itemData.item.id,

      });

This function uses the navigation hook to navigate between different screens, we then pass the selected expense id as a parameter.

Accessing Route Parameters

On the ‘Managed Expense’ screen we retrieve the id by using the useRoute hook provided by React:


const route = useRoute();

  const { id } = route.params || {}; 

The useRoute hook allows us to grab the parameters passed which in this case is the expense id selected for deletion.

Deleting the Expense from the State

To delete the item in our app we need to update the expense array stored in our Context (check out my previous post on managing app- wide state to learn more about this hook).


const deleteExpense = (expenseToDelete: Expense) => {

    setExpensesState((prevExpenses) =>

      prevExpenses.filter((expense) => expense.id !== expenseToDelete.id)

    ); 

This function takes an expense object (expense to be deleted) and re-sets the state to a new one by filtering the list of expenses to exclude the expense with the id matching the item to be deleted, this ensures our list of expenses is updated correctly.

Updating the Backend Database

In our last post we discussed using Axios to send and receive HTTP requests to update our backend database for the app. Now, let’s look at how we can use it to delete expenses from our database:


export function deletedExpense(id) {

  return axios.delete(BACKEND_URL + `/expenses/${id}.json`);

} 

By using ‘axios.delete’ we can send a deletion request to our backend database by also including the id of the expense to be deleted.

To Conclude….

By following these steps I hope you have gained a deeper understanding of the steps involved and various hooks to use in React Native in order to remove data from your backend database as well as updating the state using Context.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *