Why am I receiving the message "Error: /api/products/undefined" instead of /api/products/1?

I am facing an issue where I am trying to retrieve data of a single product from "api/products/id" using Django Rest Framework and store it in the Redux state. However, when I refresh the product's page in my React application by going to "localhost:3000/products/1", instead of getting the product with id = 1, I receive undefined data.
Upon further investigation, I discovered that the problem seems to originate from views.py.

Could this problem be related to migrations? I tried deleting database *.pyc + *.py files except init, running makemigrations and migrate again, but the issue persists.

How can I go about solving this?

Browser's console: https://i.stack.imgur.com/LxUBK.png

VS Code terminal https://i.stack.imgur.com/KnrPU.png

EDIT - added front-end If the issue lies with the front-end, it might be due to fetching problems. The request URL appears correct without any misspellings. In fetchSingleProduct, only part of the URL is included, while the rest is set in package.json as follows: "proxy": "http://127.0.0.1:8000"

singleProductSlice

const initialState = {
    status: 'idle',
    error: null,
    product: {
        reviews: [],
    }
}

// Slice logic here...

export default singleProductSlice.reducer

export const selectSingleProduct = state => state.product 

ProductScreen.js

// Component code here...

App.js

<Routes>
   <Route path='/' element={<HomeScreen />} exact />
   <Route path='/products/:id' element={<ProductScreen />} />
</Routes>

views.py

@api_view(['GET'])
def getProduct(request, pk):

    # Issue at hand...

serializer.py

class ProductSerializer(serializers.ModelSerializer):
    # Serializing logic...

models.py

# Model definition...

urls.py

urlpatterns = [
    path('', views.getRoutes, name='routes'),
    path('products/', views.getProducts, name='products'),
    path('products/<int:pk>', views.getProduct, name='product'),
]

The original path was "<str:pk>", which resulted in a ValueError, so it was changed to "<int:pk>".

Answer №1

It appears that your back-end code is functioning correctly, but the issue lies in your front-end code within the fetchSingleProduct function.


Update from the OP.

The problem causing the product id to not be retrieved is due to passing "productId" as an argument to the arrow function within the useEffect. Since this function is never called outside of its declaration, the arrow function does not receive any id and ends up being undefined.

To resolve this issue, simply remove the "productId" argument from the arrow function. The code will work properly after making this adjustment, although a warning will appear:

React Hook useEffect has a missing dependency: 'productId'. Either include it or remove the dependency array react-hooks/exhaustive-deps

To address this warning, add "productId" to the array within the second argument of useEffect. For more information, refer to: React Hook useEffect has missing dependencies. Either include them or remove the dependency array react-hooks/exhaustive-deps

The updated code for useEffect should look like this:

useEffect(() => {
        // If client doesn't have any data from server...
        if(status === 'idle') {
        // ...fetch for this data
        dispatch(fetchSingleProduct(productId))
        }
    }, [status, dispatch, productId]) 

Answer №2

It seems like there may be an issue with the react application. Double check to ensure that the API request url is accurate. The backend code appears to be functioning properly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Save Material UI Table data in an excel/csv file format

I'm currently utilizing a Table component from material-ui/core/Table in my web application. Is there a way to export it in excel or csv format? I've gone through the material UI documentation but have only come across suggestions for custom solu ...

Issue encountered while executing the build command using npm run in a ReactJS project

Encountering an error when running "craco build" The command being executed is: npm run dist When I try to run npm run build from the same folder, I face the same error. Here are the commands in the package.json file: "scripts": { "start": "npm ru ...

Guide to dynamically updating Material UI component props based on the URL parameters

On the homepage (index.js) of a Next.js website, there is an AppBar material UI component with props position="fixed". For all other pages, I would like to change the props to position="static". Rather than creating two separate compo ...

I need help figuring out how to set the country code as uneditable and also display a placeholder in react-phone-input-2 with React

How can I display the placeholder after the country code without allowing it to be edited? Currently, it's not showing up in my React functional components. Here is the code snippet: <PhoneInput className="inputTextDirLeft" ...

Utilizing the <br> tag effectively in a React map function loop

I am currently working on a project in ReactJS where I need to loop through an Array of objects using the map function. I want to separate each object on a new line by using the tag, but placing it at the end of the loop is not working for me. Can som ...

Upon successful authorization, the Node Express server will pass the access token to the React client app via OAuth in the callback

I am currently working on a node server that authenticates with a third party using oauth, similar to how Stack Overflow does. After authorizing the request and obtaining the access token and other essential information from the third party, my goal is to ...

I am currently in the process of cross-referencing the tags that have been retrieved with those that have been selected or created. If a tag does not exist

I have a collection of tags in an object, and I want to dynamically add new tags before submitting the form. Despite using vue watch, it doesn't seem to be working for me. Here is the code snippet: data() { return { blog: { blog_ti ...

Do you need to include 'passHref' when using NextJS <Link> with Semantic UI React as the child component?

After diving into the nextjs docs, I came across a section here that discusses: If the child component of Link is a function component, it's necessary to use passHref and wrap the component in React.forwardRef: As someone new to Semantic UI React, ...

The issue of Next.js redux useSelector causing HTML inconsistency

Currently, I am utilizing Next.js for the development of a React application. In order to manage the state, I have integrated redux along with redux-toolkit. A peculiar error has surfaced in the console with the message: Warning: Did not expect server H ...

Sending a function return to a React component

What I want to achieve is sending the response from an API call to a React Component and using it to generate a List. My confusion lies in how to pass the value from a function to the component. Do I require state for this process? searchMealsHandler(even ...

What strategies can I use to manage the asynchronous nature of setState()?

Currently, I am in the process of developing a simple hangman game and this is the current state of my project : static defaultProps = { maxTries: 6,// maximum incorrect tries imgs: [jpg0, jpg1, jpg2, jpg3, jpg4, jpg5, jpg6], //images changing th ...

Struggling to modify a string within my React component when the state is updated

Having a string representing my file name passed to the react-csv CSVLink<> component, I initially define it as "my-data.csv". When trying to update it with data from an axios request, I realize I may not fully understand how these react components w ...

The type 'FormikValues' is deficient in the subsequent properties compared to the type 'Exact<{'

I am currently working on a form with the following structure: import { Field, Form, Formik, FormikProps, FormikValues } from 'formik' import { NextPage } from 'next' import React from 'react' import { useCreateUserMutation } ...

Tips for implementing multiple middlewares in Next.js using the middleware.ts script

In the development of my Next.js project, I am exploring the implementation of multiple middleware without depending on external packages. Although I have seen examples of using a single middleware in Next.js with the next-connect package, I aim to achieve ...

The alignment of the DropDown menu in the AppBar is not displaying correctly

I've encountered an issue with aligning the dropdown menu while using MUI with react. I have been referencing the documentation at https://mui.com/material-ui/react-menu/#account-menu. Here is my code snippet: //** A styled component **// const Styled ...

Ensure that the hook component has completed updating before providing the value to the form

Lately, I've encountered an issue that's been bothering me. I'm trying to set up a simple panel for adding new articles or news to my app using Firebase. To achieve this, I created a custom hook to fetch the highest current article ID, which ...

Adding a new object to a nested array with MongoDB and Node.js

I'm struggling with pushing an object to a nested array, specifically in this Board document: { "boardMembers": [ "5f636a5c0d6fa84be48cc19d" ], "boardLists": [ { "cards": ...

Diverse Range of Exports Available in React Component Library

I have been working on developing a component library consisting of multiple independent components. My objective is to enable users to easily import and use these components in their projects, similar to the following: import One from 'component-lib ...

Express does not respond to a blank request and the client is left wondering on separate ports without a reply

I am facing an issue with my small react client and express server setup. The react client runs on port 3000 while the express server runs on port 3001. Whenever I click a button, a request is sent to the server. However, the POST request seems to print an ...

Adjusting the dimensions of the "overflow avatar" to be consistent with the other avatars displayed in AvatarGroup

When setting the max prop of the AvatarGroup, the additional avatar does not match the height of the other avatars. <AvatarGroup max={3}> <Avatar alt="Remy Sharp" src="/static/images/avatar/1.jpg" sx={{ width: 24, height: 24 ...