Acquiring the API through the callback function within a React application

I wrote a function that connects to an API and fetches data:

    import {API_KEY, API_URL} from "./constants";
    
export const getOperations = async (id, successCallback) => {
    try {
      const response = await fetch(`${API_URL}/tasks/${id}/operations`, {
        headers: {
          Authorization: API_KEY,
        },
      });
  
      const data = await response.json();

  
      if (data.error) {
        throw new Error('Error!');
      }
  
      successCallback(data.data);
    } catch (err) {
      console.log(err);
    }
  };

In one of my React components, I use this function to retrieve data from the specified API by passing the required ID as props.

const [operations, setOperations] = useState([])
console.log(props)
useEffect(() => {
    try {
        getOperations(data => (props, setOperations(data)))
    } catch(e) {
        console.log(e)
    }
}, [])

The issue arises because my API URL is structured differently causing a 400 error:

`...api/tasks/function%20(data)%20%7B%20%20%20%20%20%20%20%20return%20props,%20setOperations(data);%20%20%20`20%20%20%7D/operations`

I'm seeking guidance on how to format the API URL correctly for this situation:

/api/tasks/{id}/operations

Thank you in advance!

Answer №1

  • Instead of passing the callback to the function result, you can simply return the data.
export const fetchOperations = async (id) => {
    try {
      const response = await fetch(`${API_URL}/tasks/${id}/operations`, {
        headers: {
          Authorization: API_KEY,
        },
      });
  
      const data = await response.json();

  
      if (data.error) {
        throw new Error('An error occurred!');
      }

      return data.data;
    } catch (err) {
      console.log(err);
    }
  };

useEffect(() => {
  async function fetchData() {
    try {
       const data = await fetchOperations(props.id);
       setOperations(data)
    } catch(err) {
      console.log(err)
    }
  }

  fetchData();
}, [props.id])

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

Customizing the output format of Ng Date Picker beyond the standard ISO-8601

Just to clarify, I'm talking about a specific DatePicker component that can be found at the following link: Although the DatePicker interface is user-friendly and visually appealing, I'm facing an issue with the way it outputs values. While ther ...

Is there a different method I can utilize to create a conditional statement for assigning a value in JavaScript?

I have this code snippet that seems a bit unclear to me: if (!app.config.admin.examStatusId) { app.config.admin.examStatusId = exam.examStatus.dataPlus[0].id; } Do you have any suggestions on how I could rewrite this more clearly without using an if s ...

Incorporating dynamic images into Laravel using Angular

I am currently trying to dynamically input the src value of an image using Angular. Below is the code I have written : HTML : <div ng-app="myApp" ng-controller="MyCtrl"> <img src="{{asset('assets/img/'.'/'. @{{ item.name ...

Activate modifications in a distinct column?

I've been exploring a solution to achieve a similar functionality where clicking or hovering on headings in a column brings up corresponding text in another column. My idea is to use list items with a carousel for this purpose, but I'm facing so ...

Some Firebase functions are being blocked by CORS policy restrictions

When working with FireBase cloud functions, I encountered a CORS policy error that only occurs with certain methods. For instance, my GET and POST requests work perfectly fine, but when attempting to delete or edit an object, the CORS policy error immediat ...

What is the easiest way to set up a local server for deployment?

I am currently working on a research project with unique requirements that involve using private data which cannot be shared online. However, I need to create a demonstration where this data could potentially be accessed online as part of a proof of concep ...

Is it possible to set a single Tailwind breakpoint that will automatically apply to all CSS styles below it?

Responsive design in Tailwind is achieved by using the following code snippet: <div className="sm: flex sm: flex-row sm: items-center"></div> It can be cumbersome to constantly include the sm: breakpoint for each CSS rule. I want ...

When trying to convert a function component to a class component, using `npm init react-app` may result in the error `ReferenceError: React is not defined no-undef`

After running npm init react-app appname, I noticed that the file App.js was created, containing a function component: function App() { return ( <SomeJSX /> ); } I decided to change this function component into a class component like this: c ...

Trouble with passing the function variable to setState efficiently

Although I haven't worked with React for a while, it seems like this issue is more related to plain JS. Here is the setState function that I am using: // click event on parent for performance reasons ``Component:`` const [active, setActive] = useSta ...

What is the process for inputting client-side data using a web service in ASP.NET?

Currently experimenting with this: This is my JavaScript code snippet: function insertVisitor() { var pageUrl = '<%=ResolveUrl("~/QuizEntry.asmx")%>' $.ajax({ type: "POST", url: pageUrl + "/inse ...

Whenever I try to use Reactjs useState, an error always pops up

I am currently working with reactjs and utilizing the material-table to fetch data for an editable table. However, I have encountered an error similar to the image displayed. How can I resolve this issue? I have implemented useState for managing the edit ...

What are the differences between incorporating JavaScript directly into HTML and writing it in a separate file?

I need help converting this JavaScript embedded in HTML code into a standalone JavaScript file. I am creating a toggle switch that, when clicked, should go to a new page after the transformation. I am looking for the non-embedded version of the function. H ...

Error: The function registerUser from require(...) is not defined

I am facing an issue where I am trying to import the registerUser function inside router.post within the same file that houses its exported function (registerUser). However, when attempting to use it outside of this module, I receive the following error: ...

Switching the endpoint renders the middleware ineffective

I've encountered a puzzling issue with my NodeJs - Express server, which serves as the backend for my mobile application. The problem arises when I send post requests to certain endpoints like checkmail and checkusername using axios from the frontend ...

Strategies for extracting data from a third-party website that utilizes JavaScript to set the value

Before, I would use jQuery to load external website content such as html or json. Sometimes, I even utilized a proxy PHP page in order to bypass strict origin policies on certain sites. However, I've encountered an issue with some websites. In the HT ...

When the mouse hovers over the slider, the final image jumps into view

After successfully building an image slider that displays 2 partial images and 1 full image on hover, I encountered a bug when setting the last image to its full width by default. This caused a temporary gap in the slider as the other images were hovered o ...

Endless scrolling with redux and react

I'm facing an issue while trying to implement infinite scroll in a React-based application that utilizes Redux for state management. I am attempting to dispatch an action on page scroll but have been unsuccessful so far. Below is my code snippet: // ...

Can you provide guidance on securing a REST API using Google authentication?

I'm currently working on developing a REST API using NodeJS and Passport for a single-page JavaScript application. I am struggling to find the right approach to securing my REST API with Google OAuth. Can someone guide me on how to achieve this? Any ...

Creating a Next.js application that retrieves mock data and dynamically presents it on the user interface

I've been attempting to retrieve some placeholder data from an API and showcase it on the screen, but unfortunately nothing is appearing. Interestingly, the data does show up in the console, just not on the actual screen. function Shop() { const [pr ...

Error occurred while fetching image from Medium story API in Next.js

While working on my Next.js app, I encountered an issue with the Medium story API. Every time I try to fetch and display an image using the API, I receive an error message stating "upstream image response failed." The specific error code is: upstream image ...