Mastering HTTP Requests with Axios

In this post we will explore how to send and receive data using Axios as well as learning to effectively manage new states from fetched data in a React Native app.

Choosing a Backend Database

For this React Native app we will be using “Fireplace” as the backend database but you are free to choose whichever backend database you wish.

Sending the HTTP requests

We will start off with sending requests using the Axios Rest API. For our app we have created the below function to handle posting of new expenses to the backend database, the response contains an ID for the new expense.


async function storeExpense(expenseData) {

  const response = await axios.post(BACKEND_URL + "/expense.json", expenseData);

  const id = response.data.name;

  return id;

}
export default storeExpense;

Receiving HTTP requests

Now let’s move onto how we can fetch the data from our database:


export async function fetchExpense() {

  const response = await axios.get(BACKEND_URL + "/expense.json");

  console.log("Fetched date:", response.data.date);

  const expenses = [];

  for (const key in response.data) {

    const expenseObj = {

      id: key,

      amount: response.data[key].amount,

      description: response.data[key].description,

      date: new Date(response.data[key].date),

    };

    expenses.push(expenseObj);

  }

  return expenses;

The response received is formatted into an array of expense objects.

Managing State using our Context Provider

As discussed in the last post we can use the “Context” hook in React Native to effectively manage how data is shared between components in our app, in addition we can also manage the state of Context from fetched data. We can create a ‘setExpenses’ function in our Context Provider. This function will update the state whenever data is fetched.

Usage within the Application

With the functions we have created above, we can send HTTP requests to our database to store new expenses as below:


function handleAddItem() {

    storeExpense(form);

    context.addExpense({

      ...form,

    });

    setForm({ description: "", amount: "", date: "" });

    router.push("/");}

We can also fetch the data stored in our backend database and update the state in our context to display the expenses using the code below:  


useEffect(() => {

    async function getExpenses() {

      const fetchedExpenses = await fetchExpense();

      context.setExpenses(fetchedExpenses);

    }

    getExpenses();

  }, [context.addExpense]); 

Conclusion

In this post we have learnt how to send and fetch data from our backend database using Axios. As well as how to create a function to manage new states from fetched data in our Context Provider. I hope by implementing these techniques you can effectively handle communication between the frontend and backend of your React Native application.

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 *