Home > Blockchain >  unable to fetch api using the redux toolkit
unable to fetch api using the redux toolkit

Time:02-26

I have watched a tutorial to know how redux toolkit work after watching that he uses some online api providing service now when i am using it i need to customize it for my use so i have did change the name and the urls

here is my store.js

    import {configureStore} from '@reduxjs/toolkit'
import {setupListeners} from '@reduxjs/toolkit/query'
import { postApi } from './actions/productAction'

export const store = configureStore({
    reducer:{
        [postApi.reducerPath]:postApi.reducer
    },

    // middleware:(getDefaultMiddleware)=>getDefaultMiddleware().concat(postApi.middleware),

    // middleware is also created for us, which will allow us to take advantage of caching, invalidation, polling, and the other features of RTK Query.
  middleware: (getDefaultMiddleware) =>
  getDefaultMiddleware().concat(postApi.middleware),
})

setupListeners(store.dispatch)

Here i have the action file which is actually taking the action updating state

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

export const postApi = createApi({
    reducerPath:'postApi',//this is unique path which will tell the broweser where it need to store the cookie data
    baseQuery: fetchBaseQuery({
        baseUrl:'',
    }),
    endpoints:(builder)=>({
        getAllPost: builder.query({
            query:()=>({
                url:'http://localhost:5000/api/v1/products',
                method:'GET'
            })
        }),
        getPostById: builder.query({
            query: (id) =>({
                url:`posts/${id}`,
                method:'GET'
            })
        })
    })
})

export const {useGetAllPostQuery,useGetPostByIdQuery} = postApi 

The place where i am calling this function is

import React from 'react'
import {useGetAllPostQuery} from '../../actions/productAction'
// import Card from '../../components/Card';

const HomePage = () => {

  console.log(useGetAllPostQuery())
  const responseInfo = useGetAllPostQuery()

  console.log("the response i am getting is",responseInfo)
  
  return (
    <>
    <h1>Hello worls</h1>
    
  </>
  )
}

export default HomePage

my console where i am getting i dont why this error is coming the request is rejcted at the same time my post man works on that enter image description here

The error expanded image

enter image description here

The actual issue is

enter image description here

CodePudding user response:

looks like it is not getting the Url Try adding your base URL like this

export const postApi = createApi({
    reducerPath:'postApi',
    baseQuery: fetchBaseQuery({
        baseUrl:'http://localhost:5000/',  //added your base url
    }),
    endpoints:(builder)=>({
        getAllPost: builder.query({
            query:()=>({
                url:'api/v1/products' // this should take only one argument
            })
        }),
        getPostById: builder.query({
            query: (id) =>({
                url:`posts/${id}`  // this should take only one argument
            })
        })
    })
})

For more Details, you can refer to here rtk query

CodePudding user response:

Bro, I watch that tutorial too, it is old. Here is the correct way to fetch. Please let me know if this answer help you. And also you auto complete to import. You're not importing from the right place if you follow that tutorial.

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

import React from 'react'
import {useGetAllPostQuery} from '../../actions/productAction'
// import Card from '../../components/Card';

const HomePage = () => {

  console.log(useGetAllPostQuery())
  //You can also desctructure it like this {data:responseInfo}, you must not directly change the value. 
  const {data} = useGetAllPostQuery()


  
  return (
    <>
    //Then you check if data exist first because the initial value is empty. you can also check like this <div>{data?.map((my data)=> <>...</>))}</div>
    
    <div>{data && data.map((mydata, i)=> (
    //You can tag on what you want to display. if you want to display names, then you can say madata.name
    <p key={i}>{mydata}</p>
    ))}</div>
    
  </>
  )
}

export default HomePage

To solve cors errors, try this:

Create vercel.json under the root folder.

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

{
  "headers": [
    {
      "source": "/api/(.*)",
      "headers": [
        { "key": "Access-Control-Allow-Credentials", "value": "true" },
        { "key": "Access-Control-Allow-Origin", "value": "*" }, // Change this to specific domain for better security
        {
          "key": "Access-Control-Allow-Methods",
          "value": "GET,OPTIONS,PATCH,DELETE,POST,PUT"
        },
        {
          "key": "Access-Control-Allow-Headers",
          "value": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version"
        }
      ]
    }
  ]
}

Go to /api/index.js file.

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

export default async (req, res) => {
  const { method } = req;

  // This will allow OPTIONS request
  if (method === "OPTIONS") {
    return res.status(200).send("ok");
  }
};

CodePudding user response:

I was not looking console properly the main issue was that the backend was not allowing me to query the api which is kind strange i have not find this using axios means i not need to use cors to access api using axios but if you are doing it using redux tool kit then you need to use cors

npm install cors 

then add these line in your main backend file

const cors = require('cors');
const express = require('express');
const app = express();
app.use(cors());
  • Related