1

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

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Hessah
  • 192
  • 3
  • 12
  • that means the endpoint is protected are you sure you dont need some access token to access that end point – onifade boluwatife Sep 28 '21 at 10:27
  • Aside from the 401 error, your `console.log` statements will never show the data, because A) it **hasn't been retrieved yet** when you call them, and B) it wouldn't be in those variables anyway (see: https://stackoverflow.com/questions/41446560/react-setstate-not-updating-state). When you set the state, your component function will get called again, and in that new call you'll get back the state from `useState`. – T.J. Crowder Sep 28 '21 at 10:31

1 Answers1

0

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

Asif vora
  • 3,163
  • 3
  • 15
  • 31
  • 1
    The main problem in the question is a bit buried, but it's a 401 from the server, not the React state issue. If it **were** the React state issue, the question would be a duplicate of https://stackoverflow.com/questions/41446560/react-setstate-not-updating-state and not need its own answers. – T.J. Crowder Sep 28 '21 at 10:32
  • Axios treats 401 as an error It won't allow you to parse the body so you will have to judge according to status code – Makarand Sep 28 '21 at 10:44
  • 1
    Indeed! it is solved by passing an authentication token to my endpoint to ensure validation... Thanks! – Hessah Sep 30 '21 at 10:19