简体   繁体   中英

Not able to get data from AXIOS inside useEffect()

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

You do not directly access the data in the useEffect method when you set it using the hooks.

Example:

  useEffect(() => {
      setTitle("This is title");
      console.log("Title: ", title);                //OUTPUT: Title: undefined
  }, [match.params.id]);

You can add a dependency and check it when the title value is changed

  useEffect(() => {
      console.log("Title: ", title);                //OUTPUT: This is title
  }, [title]);

Edit the answer

If API's throw the 401 means Unauthorized . You need to pass authentication token in your API call for validation of the API request from the backend side.

Here you can check how to pass token in API calls. Sending the bearer token with axios

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM