What is the best method for retrieving a single resource from the backend using Typescript and createAsyncThunk by obtaining the params ID?

I am currently facing an issue while trying to fetch a single resource (one to-do) from my backend. I am struggling to set up my store in the frontend and cannot seem to find the req.params.id as I would typically do with regular Javascript + Redux thunks. I referred to some documentation at https://redux-toolkit.js.org/api/createAsyncThunk and attempted to replicate it in my todoSlice file. However, I encountered the following error: "Argument of type '(todoId: string, thunkApi: GetThunkAPI<{}>) => Promise' is not assignable to parameter of type 'AsyncThunkPayloadCreator<Todo, void, {}>'. Types of parameters 'todoId' and 'arg' are incompatible. Type 'void' is not assignable to type 'string'." I am uncertain about how to retrieve the id from parameters using Typescript and would greatly appreciate any assistance. I have provided the current setup of my files below:

On the left side: my client-side thunk. On the right side: my backend server controller. https://i.sstatic.net/3upv1.png

This is my todoSlice code:

interface TodoState {
  todos: Todo[] | null;
  isFetching: boolean;
  singleTodo: Todo | null;
  errors: any;
}

export const getOneTodo = createAsyncThunk<Todo>(
  'TODO/FETCHONE',
  async(data, thunkApi) => {
    try {
      const res = await axios.get(`http://localhost:5001/api/todos/`);
      thunkApi.dispatch(getOneTodo());
      return res.data;
    } catch(e) {
      return thunkApi.rejectWithValue(e)
    }
  }
);

Below is my todo router controller:

// get one to-do
export const getTodo = async (req: Request, res: Response) => {
  try {
    const task = await Todo.findById(req.params.id);
    res.status(200).json(task);
  } catch(e) {
    res.status(500).json({ err: e });
  }
};

Answer №1

After diving into some old code, I discovered a way to optimize the following function:

export const fetchSingleTodo = (todoId: string) => createAsyncThunk<Todo>(
  'TODO/FETCHONE',
  async(_, thunkApi) => {
    try {
      const response = await axios.get(`http://localhost:5001/api/todos/${todoId}`);
      thunkApi.dispatch(fetchSingleTodo(todoId));
      return response.data;
    } catch(error) {
      return thunkApi.rejectWithValue(error)
    }
  }
);

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

Having trouble with MongoDB aggregation project and cond functionality?

I encountered a "MongoServerError: Invalid $project :: caused by :: Unrecognized parameter to $cond: $if" error with this code. Can anyone help me understand what the issue is and how to resolve it? { $project: { _id: 1, date: ...

Showing the results of functions on a pre-existing EJS layout

I'm trying to figure out how to display a value from a JS file (indexRoutes.js) in an input box on an EJS template (calculator.ejs). I've included the script through a footer that I created. Here is the code for the JS Function: router.post(&quo ...

Error encountered in file.js line 1: Unexpected token '<' in ExpressJS with EJS Integration

I am currently facing an issue with my ExpressJS server using the ejs template engine to run a Blockly app and a threejs map on a web page. The problem arises when I navigate to /applications/:slug to load a saved application, causing the app.ejs file to c ...

The border of the Material UI Toggle Button is not appearing

There seems to be an issue with the left border not appearing in the toggle bar below that I created using MuiToggleButton. Any idea what could be causing this? Thank you in advance. view image here view image here Just a note: it works correctly in the ...

Leveraging string interpolation in Typescript with a string sourced from a file

After diving into Typescript, I came across some intriguing information on template strings. One question that popped into my mind is whether these template strings can be utilized when reading a string from a file, just like this: let xmlPayloadTemplate ...

What is the ideal configuration for Typescript within ASP.NET 4 MVC 5 on Visual Studio 2015?

Currently, I am in the process of integrating a TypeScript project into a VS2015 MVC 5 project (which is based on ASP.NET 4, specifically not asp.net 5 or asp.net 6 - only the MVC portion is version 5). All aspects of my query pertain solely to this target ...

typescript: the modules with relational paths could not be located

As part of a migration process, I am currently converting code from JavaScript to TypeScript. In one of my files 'abc.ts', I need to import the 'xyz.css' file, which is located in the same directory. However, when I try to import it usi ...

Typescript combined with MongoDB models

One common issue I have encountered involves a method used on my repository: async findByEmail(email: string): Promise<User | null> { const user = await UserModel.findOne({ email }); if(!user) return null; ...

leaving code block using Express and Node

My code is displayed below: // Implement the following operations on routes ending with "users" router.route('/users') .post(function(req, res, next) { var user = new User(); user.username = req.body.username; user.p ...

Creating a universal timer at the application level in Angular

Is there a way to implement a timer that will automatically execute the logout() function in my authentication.service at a specific time, regardless of which page I am currently on within my application? I attempted to create a timer within my Authentica ...

Evaluating an express.js application in a custom environment using a simulated database

Here is the setup for my web app: In my db.js file: mongoose = require('mongoose'); db = mongoose.createConnection("..."); playerSchema = new mongoose.Schema({ // my schema stuff }); exports.Player = db.model("player", playerSchema); My rout ...

Promise.allSettled() - Improving resilience through retry mechanisms for concurrent asynchronous requests

TL;DR: I'm seeking advice on how to handle multiple promise rejections and retry them a specified number of times when using Promise.allSettled() for various asynchronous calls. Having come across this article: I was intrigued by the following state ...

Node.js encountering req.body as undefined when using form-data as the content-type

After creating a small demonstration for this form-data passing API, I attempted to test it using Postman. However, I encountered an issue where no data was being retrieved. Code const http = require("http"); const express = require("expres ...

Greetings, I am a newcomer to Prisma and am transitioning from Mongoose. I am seeking guidance on how to create a VerificationToken model where the expires at field automatically updates to the current time plus 10

Is there a way to conceal the password field in Prisma similar to using select false in Mongoose? Also, how can I set up a VerificationField model that automatically generates an expires at field with a value 10 minutes from the current date? I'm loo ...

No content in webpack result file when using express and react

Trying to implement webpack into the basic react comment list tutorial has been a bit of a challenge for me. Everything seems to be functioning properly, but my output file never actually contains any content. Let's take a look at my webpack configur ...

New feature incorporated at the end of choices in MUI auto-suggest widget

Currently, I'm working on enhancing a category adder feature. Previously, I had limited the display of the "add category chip" to only appear for the no-options render scenario. However, I came across an issue where if there was a category like "softw ...

Why is it that TypeScript does not issue any complaints concerning specific variables which are undefined?

I have the following example: class Relative { constructor(public fullName : string) { } greet() { return "Hello, my name is " + fullName; } } let relative : Relative = new Relative("John"); console.log(relative.greet()); Under certain circum ...

Guide for incorporating Twitter and Facebook API-style cursor-based pagination in MongoDB with the official MongoDB client using Node.js

In my current project, I am tackling the challenge of incorporating pagination without displaying duplicate data on different pages when new data is added or removed. The traditional offset-based method using skip and limit to paginate data can be found i ...

Exploring the functionality of the `super()` method in TypeScript

I'm trying to enhance the standard JavaScript Error class by adding another property called code, but for some reason, TypeScript is not allowing me to do so. Here is the code snippet: export class HttpError extends Error { public message: string ...

A TypeScript function designed to only process arrays consisting of objects that contain a specific property determined by another parameter, with the requirement that this property

function retrieveObjectRow<T = string>( arrayData: { [key: T]: number; [key: string]: unknown; }[], targetValue: number, specifiedField: T ): typeof arrayData[number] | null { for (let i = 0; i < arrayData.lengt ...