Tips for utilizing the transformResponse function in RTK Query to modify the server's response

Hi, I'm a newbie to RTK Query and I have a question. I made an API call that returns an array of arrays of objects, and I'd like to leverage the transformResponse option to flatten the API response into a single array of objects.

Below is the code snippet:


getStocks: builder.query({
    query: credentials => ({
        url: `stocks`,
        body: {credentials},
        transform: response => {
            console.log(response);
            return response;
        },
    }),
   })

This is the data structure of the API response:


[
    // Arrays of information for different stocks
]

I aim to format the data as follows:

Symbo Close
AAPL 120
BYD 130
CSC 123
SEC 433

Answer №1

After some research on Stack Overflow, I came across a solution that inspired me to create my own custom approach.

To implement this, I developed a unique function called baseQueryWithChange that allows for a global transformation of all query responses by wrapping it around the existing baseQuery.

A specialized function for transforming API responses:

export const changeResponse = async (list) => {
    const dataArray = list.data
    console.log(dataArray) // 10 elements
    
    const finalArray = await dataArray.filter((each) => each.length !== 1) // 6 elements

    const normalizeData = (data) => {
        return data.flatMap((d) => {
            return { ...d[0], ...d[1] };
        });
    };

    const latestList = normalizeData(finalArray)

    console.log(normalizeData(finalArray)); // 6 elements

    return latestList
}

The foundation of the baseQuery:


import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
// import function to transform API response
import { changeResponse } from "../../constants/changeResponse";

const baseQuery = fetchBaseQuery({
    baseUrl: "http://localhost:3500"
})

const baseQueryWithChange = async (args, api, extraOptions) => {
    let result = await baseQuery(args, api, extraOptions);
    if (result.data) {
        result.data = changeResponse(result.data)
        console.log(result.data)
    }
    return result
}

export const apiSlice = createApi({
    baseQuery: baseQueryWithChange,
    endpoints: builder => ({})
})

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

Incorporate Bookmarklet into GitHub README.md

Trying to add a Bookmarklet to a Github README.md, but encountering issues with the markdown code: [Bookmarklet](javascript:alert('not-working')) It appears that the javascript in the link is being stripped out from the compiled output. Is this ...

Problem with Selenium WebDriver: Some HTML elements are not being displayed

I am currently working on a python web scraper. Here is the code I have written: from selenium.webdriver.chrome.options import Options from selenium import webdriver from bs4 import BeautifulSoup chrome_options = Options() chrome_options.add_argument(&qu ...

Troubleshooting JavaScript Date Problem with Internet Explorer 7

When I retrieve a Date from a web method, it comes in the format of "Mon Sep 30 07:26:14 EDT 2013". However, when I try to format this date in my JavaScript code like this: var d= SomeDate.format("MM/dd/yyyy hh:mm:ss tt"); //Somedate is coming from the we ...

Merely using the stdio library alone is insufficient for a basic "for" command to function properly

In my previous inquiry (refer to the third paragraph at Problems in code or my IDE/comp is bugged?), I am using the same machine and IDE to test the following code: #include <stdio.h> #define n 3 int main() { int i; float values[n],sumval,sv ...

Executing NodeJS commands and Linux commands via Crontab scheduling

I have an EC2 AWS instance where various commands and scripts work perfectly, but do not execute within a crontab. The Crontab contains: 15 03 * * * pythonscript1.py 45 03 * * * pythonscript2.py 00 05 * * * gsjson 1z5OlqsyU5N2ze1JYHJssfe1LpKNvsr4j8TDGnvyu ...

Having trouble with a CSS selector within a JSP page when attempting to dynamically set the background of a div

Currently, I am in the process of developing an image uploader feature that will enable users to upload images and set them as backgrounds for a div element. Specifically, the .mm11 class represents a post-it style card that initially does not have a backg ...

The custom error page in NextJS is failing to display

In my custom pages/404.ts file, I have coded the following: export default function NotFound() { return <h1>404 - Page Not Found</h1> } Additionally, there is another page that displays a 404 error when the organization is null: import Error ...

Guide to creating a route of minimal values within the matrix

Can someone help me figure out how to draw a path that follows the lowest numbers in this matrix? Here is an image for reference: https://i.sstatic.net/B9Wid.png I am looking for something similar to this example: https://i.sstatic.net/AsfeC.png I am fam ...

Having trouble with locating an image within an array in React JS

I am currently working on a project in React JS where I need to import images into an array. The goal is to display these images one by one by mapping through the array. Unfortunately, I am facing issues with resolving the images properly. I believe it may ...

Is there a method in JavaScript or jQuery that can be used to detect changes in the width of a div element while debugging HTML

Is there a method to detect changes in the width of a div element when debugging HTML using JavaScript or jQuery? I am experiencing a situation where a div's size is being altered by some CSS rules, but I am unable to identify the source even when ana ...

"Directional Light in three.js that Tracks Alongside the Camera

I'm encountering an issue with Three.js and lighting that follows a camera. I am utilizing orbit control for mouse movement. In release 66, the following code used to function properly: light = new THREE.DirectionalLight( 0xffffff, 1 ); lig ...

I require a way to decelerate the speed of the roulette wheel's rotation

For my assignment, I'm tasked with creating a roulette spin wheel code in JavaScript without using any plugins. I need to incorporate some conditions before executing the code, particularly for slowing down the speed of the roulette spin. Additionally ...

The regular expression is functioning correctly in the browser, however, it is encountering issues when

My task involves identifying certain strings from given variables. Let's say I have a variable: var x = 'elseif testing'; My goal is to extract the value "testing" from this string, so I came up with the following code snippet: x.match(/^ ...

Incorporating user input into a form using NodeJS and Angular

I am currently facing an issue while trying to add a new entry using NodeJS with an Angular form. Every time I click on create, the data is not being inputted into the database. To address this, I included the angular.toJson function to convert the input i ...

What is the proper way to enable the Google Analytics cookie only once another consent cookie has been set and is marked as "true"?

I am currently using React/Nextjs on my website along with the react-cookie-consent library. This setup generates a pop-up where users can agree to the cookie policy, and if they do, a CookieConsent with the value "true" is set. In addition to this, I wis ...

Tips for transferring a geolocation lat lng to the `ll` property of a different function in React

I have a Geolocation.js file that retrieves the geolocation data and logs it to the console. This file is imported into an index.js file and I need to use the lat and lng values that are logged to replace the hardcoded values in the ll parameter in the fol ...

Is it possible to use header() function in a file that is being accessed through

In a specific package, there is a crucial file that verifies session data and redirects the user to the login page with an error message if no valid session exists, using header("Location:" . $var);. This particular file is included in almost all files wi ...

What is the mechanism by which the called function interprets the memory location of an array in call by reference?

Seeking a deeper understanding of passing an array by reference, I delved into an example from a book. Through experimentation in Code Blocks and some additional reading, a few key concepts became clear to me. First, when passing by value, the original v ...

Using Javascript to select a radio button in a form depending on the value entered in a text box

I have a form that interacts with a Google Sheet to insert and retrieve data. For instance, the form contains two radio buttons: <input id="Rdio_1" name="RdioSelect" type="radio" class="FirstCheck" value="1" onchange="RadioValInsert ()"/> < ...

Adjust the background hue while scrolling (scrolling feature not functioning properly)

Seeking assistance with changing the background color of a component based on user scrolling behavior. I have attempted to achieve this using the following code snippet: const [mainColor, setMainColor] = useState('red') const listenScrollEve ...