1

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

2
  • 1
    Can you also add the expandable error object image and your base URL is empty Commented Feb 25, 2022 at 14:40
  • i have updated the question kindly check Commented Feb 25, 2022 at 14:43

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

9 Comments

Well i have first try this only because i am getting the error then i try that
what error are you getting?
the same which i am getting now i also feel that there might something wrong with the url so i think to make it blank and add all in one line that also give the same error
i was able to fetch data with axios
remove the method get from both the builder query ` method:'GET'` and try again but keep the base URL it is standard way to do it
|
1

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");
  }
};

10 Comments

i have followed the tutorial but now i want to do my work not what he do so i have my code base
Were you able to get the data?
You should put slash '/' at the back of localhost:3000/
I will edit the answer for you now
Would you mind marking the answer?
|
0

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.