I want to fetch data from server using “id”.. but when I’m doing so i get this error.
Following is my frontend part that is used to get data from server.
“ShowBook” I made this to get data from server using “id”.
import React ,{useEffect,useState} from 'react';
import axios from 'axios';
import { useParams } from 'react-router-dom';
import BackButton from '../components/BackButton';
import Spinner from '../components/Spinner';
const ShowBook = () => {
const [books, setBooks] = useState({});
const [loading, setLoading] = useState(false);
const { id } = useParams();
useEffect(() => {
setLoading(true);
axios
.get(`http://localhost:5555/books/${id}`)
.then((response) => {
setBooks(response.data);
setLoading(false);
})
.catch((error) => {
console.log(error);
setLoading(false);
});
},[])
return (
<div className='p-4'>
<BackButton/>
<h1 className='text-3x1 my-4 '>Show Book</h1>
{loading ?(
<Spinner/>
):(
<div className='flex flex-col border-2 border-sky-400 rounded-x1 w-fit p-4'>
<div className='my-4'>
<span className='text-x1 mr-4 text-grey-500'>ID</span>
<span >{books._id}</span>
</div>
<div className='my-4'>
<span className='text-x1 mr-4 text-grey-500'>Title</span>
<span >{books.title}</span>
</div>
<div className='my-4'>
<span className='text-x1 mr-4 text-grey-500'>Author</span>
<span >{books.author}</span>
</div>
<div className='my-4'>
<span className='text-x1 mr-4 text-grey-500'>Publish Year</span>
<span >{books.publishYear}</span>
</div>
<div className='my-4'>
<span className='text-x1 mr-4 text-grey-500'>Create time</span>
<span >{new Date(books.createdAt).toString()}</span>
</div>
<div className='my-4'>
<span className='text-x1 mr-4 text-grey-500'>Last Updated time </span>
<span >{new Date(books.updatedAt).toString()}</span>
</div>
</div>
)
}
</div>
)
}
export default ShowBook
The following is my backend part (routes ).
import express from "express";
import { Book } from "../models/bookModel.js";
const router = express.Router();
//route to save a new book
router.post("/", async (req, res) => {
try {
if (!req.body.title || !req.body.author || !req.body.publishYear) {
return res.status(400).send({
message: "send all required fields: title, author, publishYear",
});
}
const newBook = {
title: req.body.title,
author: req.body.author,
publishYear: req.body.publishYear,
};
const book = await Book.create(newBook);
return res.status(201).send(book);
} catch (error) {
console.log(error.message);
res.status(500).send({ message: error.message });
}
});
//route to get all books from database
router.get("/", async (req, res) => {
try {
const books = await Book.find({});
return res.status(200).json({
count: books.length,
data: books,
});
} catch (error) {
console.log(error.message);
res.status(500).send({ message: error.message });
}
});
//route to get one book from database by ID
router.get("/:id", async (req, res) => {
try {
const { id } = req.params;
const book = await Book.findById(id);
return res.status(200).json(book);
} catch (error) {
console.log(error.message);
res.status(500).send({ message: error.message });
}
});
//route to update a book
router.put("/:id", async (req, res) => {
try {
if (!req.body.title || !req.body.author || !req.body.publishYear) {
return res.status(400).send({
message: "send all required fields: title, author, publishYear",
});
}
const { id } = req.params;
const result = await Book.findByIdAndUpdate(id, req.body);
if (!result) {
return res.status(404).json({ message: "Book not found" });
}
return res.status(200).json({ message: "Book updated successfully" });
} catch (error) {
console.log(error.message);
res.status(500).send({ message: error.message });
}
});
//route to delete a book from database by ID
router.delete("/:id", async (req, res) => {
try {
const { id } = req.params;
const result = await Book.findByIdAndDelete(id, req.body);
if (!result) {
return res.status(404).json({ message: "Book not found" });
}
return res.status(200).json({ message: "Book deleted successfully" });
} catch (error) {
console.log(error.message);
res.status(500).send({ message: error.message });
}
});
export default router;
This Shows my Schema, i made :-
import mongoose from "mongoose";
const bookSchema = mongoose.Schema(
{
title:{
type: String,
required:true
},
author:{
type: String,
required:true
},
publishYear:{
type: Number,
required:true
}
},
{
timestamps: true
},
);
export const Book = mongoose.model('CAT', bookSchema);
Following is my APP.js file :-
import React from 'react'
import { Routes , Route} from 'react-router-dom';
import Home from './pages/Home';
import CreateBook from './pages/CreateBook';
import DeleteBook from './pages/DeleteBook';
import EditBook from './pages/EditBook';
import ShowBook from './pages/ShowBook';
const App = () => {
return (
<Routes>
<Route path ='/' element={<Home/>}/>
<Route path ='/books/create' element={<CreateBook/>}/>
<Route path ='books/details/:id' element={<ShowBook/>}/>
<Route path ='books/edit/:id' element={<EditBook/>}/>
<Route path ='books/delete/:id' element={<DeleteBook/>}/>
</Routes>
)
}
export default App
I checked all route, API and endpoints, everything seems fine.
If i use http://localhost:5173/books/details/662c84a93e1918ec47b33047
this i get the data from server.
But if I am passing the {_id} that makes my url like :-http://localhost:5173/books/details/undefined
.
The problem what i think is somehow id is not being passed properly.
RITIK SINGH is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.