I'm trying to GET data from axios inside useEffect() in React. I tested the backend it's working fine, but in frontend I'm getting an error 401 (Unauthorized)
React Code:
import { useEffect, useState } from "react";
import axios from "axios";
function UpdateItem({ match, history }) {
const [title, setTitle] = useState();
const [description, setDescription] = useState();
...
useEffect(() => {
const fetching = async () => {
console.log("I'm there !!!"); //OUTPUT: I'm there !!!
const { data } = await axios.get(`/items/${match.params.id}`);
console.log("data from useEffect: ", data); //OUTPUT:
setTitle(data.title);
setDescription(data.description);
};
fetching();
console.log("Title: ", title); //OUTPUT: Title: undefined
console.log("Description: ", description); //OUTPUT: Description: undefined
console.log("I'm here !!!"); //OUTPUT: I'm here !!!
}, [match.params.id]);
...
}
Backend Code:
server.js
app.use("/items", itemRoutes);
itemRoutes.js
const asyncHandler = require("express-async-handler");
router.route("/:id").get(
asyncHandler(async (req, res) => {
const wantedItem = await Item.findById(req.params.id);
if (wantedItem) {
res.json(wantedItem);
} else {
res.status(404).json({ message: "Requested item is not found!" });
}
res.json(wantedItem);
});
)
and the error I'm getting:
GET http://localhost:3000/items/614dbaea5338fa8622d8e3df 401 (Unauthorized)
I'll be glad if anyone can help me to figure out the mistake