I'm encountering an issue when attempting to send a parameter to a function within a typescript code

Recently, I started using Typescript and encountered an issue with passing arguments to a function in Typescript. This particular function is triggered when rendering a form modal. However, I keep receiving two errors:

"Argument of type 'Promise<AxiosResponse>' is not assignable to parameter of type '(data: Record<string, unknown>) => Promise'."

"Type 'Promise<AxiosResponse>' provides no match for the signature '(data: Record<string, unknown>): Promise'."

  function openModal(activity) {
    const data = ref({
      name: activity.name,
    })     

    formRender.render(activity, updateActivity(activity.id,{name:data.value.name}))
  }

This is the updateActivity function:

export function updateActivity(id: number, data: Record<string, unknown>) {
 return http.patch(`/${id}`, { name: data.name })
}

The FormRender component:

 export function FormRender<T extends Record<string, unknown>>(formName: string) {
  return {
   render(formAttributes: T | Record<string, unknown>, service: (data: T) => Promise<unknown>) {
     dialog({
      component: FormRender,
      componentProps: {
        formName,
        formAttributes,
        service
     },
  })
},

Answer №1

export function updateActivityData(id: number, info: Record<string, unknown>) {
 return http.patch(`/${id}`, { name: info.name })
}

This specific function will give you back a

Promise<AxiosResponse<any, any>>
. Keep in mind that it is an async function requiring you to use await to retrieve the value after making the HTTP request.

To extract data from this response type, remember to await it first before accessing the desired data property within the axios response:

export async function updateActivityData(id: number, info: Record<string, unknown>) {
  const response = await http.patch(`/${id}`, { name: info.name })
  return response.data // You might need additional parsing like JSON.parse depending on the API response
}

Now, as the service parameter is defined as a function, you can simply pass a function that invokes this method:

formRender.render(activity, (data) => updateActivityData(activity.id, {name:data.value.name}))

Check out this functioning example without any type errors

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

Verifying if a JavaScript textarea is empty

How can I make a textarea have a visible border around it when the string is empty, without needing to first input and delete text? Here is my current code: $("#message-box").on("keyup", function(){ var charCount = $("#message-box").val().length; ...

What is preventing targeting a class in React?

I'm having trouble targeting className in react. I attempted to target it using div className="navbar"> and .navbar { align-items: center; } but it's not working. div{ display: block; background-color: rgb(211, 57, 57); ...

Enable v-model input functionality by hitting the enter key

I am currently using Vue for my project The search input bar on my page is currently filtering the results after every letter I type. I want it to filter only after I press the enter key. Could someone please assist me with this? <template> < ...

Error 19: Constraint violation - duplicate entry detected

While trying to set up my app, create a local database, and insert the very first user who has logged in locally, I encountered an error message at a specific point in the code. Here's where it happened: angular.module("greenApp") .service("d ...

Identifying Hashtags with Javascript

I am trying to identify hashtags (#example) in a string using javascript and convert them to <a href='#/tags/example'>example</a> Currently, I have this code: var text = '#hello This is an #example of some text'; text.r ...

Mastering the Art of Binding Option Data from API Responses in Vue.js

Just starting out with Vue.js and attempting to bind option data from an API response. I've made an axios call in the mounted() hook and assigned the companies data from the response, but I'm encountering errors as shown below. 373:11 error ...

jQuery's display function is being obstructed by a lengthy operation

$('#someid').show(); someLongRunningFunction(); This snippet indicates that the element with id $('#someid') will be displayed only after the function someLongRunningFunction completes its execution. Is there a possible way to modify t ...

Having trouble with a 400 Bad Request error when sending a POST request from my Vue application to my Rails API

Currently delving into the world of Rails and Vue, I decided to take on a small project involving a basic Rails API and Vue app to practice making GET and POST requests from my Vue app to the Rails API. While GET requests are working smoothly, I'm enc ...

Showing options in the navigation bar upon user authentication with Passport in NodeJS

When a user is connected, I want the navbar to display "Profile of: {USER}", otherwise it should show a set of Sign up/Login tabs. The challenge lies in using EJS with separate "head.ejs" and "header.ejs" sections placed in a /partials folder within the / ...

Ensure that react-native-google-places-autocomplete is assigned a specific value rather than relying on the default value

I am currently using a functional <TextInput>: <TextInput placeholder="Location" value={props.locationInput.toString()} onChangeText={location => props.updateLocationInput(location)} /> Initially, the props.locationIn ...

Understanding the mechanics of async/await and Promise in TypeScript

Trying to wrap my head around how async, await, and promises work with this simple function. function delay(ms: number) { return new Promise<void>(function(resolve) { setTimeout(resolve, ms); }); } async function asyncAwait() { c ...

Rotating 3D cube with CSS, adjusting height during transition

I'm attempting to create a basic 2-sided cube rotation. Following the rotation, my goal is to click on one of the sides and have its height increase. However, I've run into an issue where the transition occurs from the middle instead of from the ...

The attribute 'commentText' is not found within the 'Comment' data type

Currently, I am immersed in building a user-friendly social network application using Angular 12 for my personal educational journey. Running into an error has left me puzzled and looking for assistance. About the Application: The home page (home.compone ...

Why is my snapshot returning null, even though there are values in the Firebase Database?

I am currently facing an issue in my code related to the snapshot. Specifically, I am trying to retrieve the value of quantity from my Firebase Database. Here's a snapshot of my database: https://i.sstatic.net/qN6m4.jpg and https://i.sstatic.net/Gw ...

Google App Engine does not properly interpret PHP code when making AJAX requests

I am currently facing an issue with using AJAX request on Google App Engine. In my local development environment, everything works fine and the request is correctly interpreted. However, when I deploy the code to production, the AJAX request renders the co ...

Error: $result has not been defined in this context

The following code snippet is designed for fetching JSON results from a cross-domain request and displaying them in a select menu. However, there appears to be an issue where the $result variable is not recognized, causing a console log error: Uncaught R ...

Using TypeScript in Node.js to iterate through an asynchronous forEach loop

I attempted to integrate a database operation within an async forEach loop with the following code snippet: let successCounter = 0; let failureCounter = 0; let myData = [101, 102, 104, 105]; myData.forEach(async data => { let response = awai ...

Error: The React Hook "useX" should not be invoked at the top level of the code

I am facing a challenge while attempting to transfer the exception handling logic from the component to my service class: Login.tsx: import { useSnackbar } from "notistack"; // ... const Login = () => { const { enqueueSnackbar } = useSnack ...

Obtain the index by clicking on an element within an HTMLCollection

Within my HTML code, I have 9 <div> elements with the class ".square". I am looking to make these divs clickable in order to track how many times each one is clicked and store that information in an array. For example, if the fifth <div> is c ...

Retrieve the source code of a webpage by accessing its URL with JavaScript through the use of JSONP

To extract the source code from a URL web page using JSONP, you can use the following code snippet: <script type="text/javascript"> var your_url = ''; $(document).ready(function(){ jQuery.ajax = (function(_ajax){ var protocol = location. ...