Search code examples
javascriptreactjsreact-nativereact-reduxredux-toolkit

Redux Toolkit Returns FETCH ERROR, Network Request Failed In React Native


I am using React-Native for the frontend of my project, and using Redux-Toolkit to parse the data to the backend. I am also using an external API in my backend, and the backend communication with the external API is working well. However, when I try to call the function in the frontend, it returns Network Request Failed. Can someone help me to pinpoint where in the codes did I make a mistake?

Here is the snippet to my APISlice in the frontend

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

const baseUrl = 'http://localhost:8080/'

export const apiSlice = createApi({
    reducerPath: 'api',
    baseQuery: fetchBaseQuery({ baseUrl }),
    endpoints: (builder) => ({
        // Payments
        createTopupIntent: builder.mutation({
            query: (data) => ({
                url: 'topup/intents',
                method: 'POST',
                body: data,
            })
        })
    })
})

export const {
    useCreateTopupIntentMutation,
} = apiSlice

Here is the code to the index.js stored inside the store folder in the frontend.

import { configureStore } from '@reduxjs/toolkit';
import { apiSlice } from './apiSlice';

export const topup = configureStore({
  reducer: {
    api: apiSlice.reducer,
  },
  // Adding the api middleware enables caching, invalidation, polling,
  // and other useful features of `rtk-query`.
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(apiSlice.middleware),
});

And this is where the function is actually called in the frontend.

import { useCreateTopupIntentMutation } from '../../store/apiSlice'

const total = navigation.getId("amount")
  const [createTopupIntent] = useCreateTopupIntentMutation()

  const onCheckout = async () => {
    // 1. Create a payment intent
    const response = await createTopupIntent({
      amount: Math.floor(total * 1000),
    })
    console.log(response)

And here is the routes in my backend index.js.

const express = require('express')
const topupRoutes = require('./src/router/topupRoutes')
const bodyParser = require('body-parser')

const app = express()
const PORT = 8080

app.use(bodyParser.json())
app.use('/topup', topupRoutes)

app.get('/', (req, res) => {
    res.send('<h2>Hello World</h2>')
})

app.listen(PORT, "0.0.0.0",  () => {
    console.log('API is listening on PORT', PORT)
})

This is the route endpoint specification snippet.

const express = require('express')
const router = express.Router()
const stripe = require('stripe')(
    'STRIPE_SECRET_KEY'
    )

// ALL ROUTER ENDPOINTS
router.post('/intents', async(req, res) => {
    try {
        // CREATE TOP UP INTENT
        const topupIntent = await stripe.paymentIntents.create({
            amount: req.body.amount, // INTEGER
            currency: 'usd',
            automatic_payment_methods: {
                enabled: true
            }
        })
    // RETURN THE SECRET
    res.json({topupIntent: topupIntent.client_secret})
    } catch (e) {
        res.status(400).json({
            error: e.message,
        })
    }
})

module.exports = router

Solution

  • I solved the issue by changing localhost to my local IP address that I am currently connected to.