What is the best way to transfer an array of objects between two components in React?

I've exhausted all the solutions found online, but I'm still facing a persistent issue. Despite my efforts, whenever I try to log information in another component, it keeps showing as undefined.

(Just to clarify, the data being dealt with is an object array)

Snippet from the first component:

  goToCart(): void{
let params = { queryParams: this.cart };
this.router.navigate(['/cart', params]);

}

Snippet from the second component:

  ngOnInit(): void {
this.router.queryParamMap.subscribe(params => this.cart = params.getAll("cart"));
console.log(this.cart[0]);

}

Answer №1

There are three errors in this code snippet

The first mistake is that you need to send a string, not an array or object. To do this, use JSON.stringify

The second error is that you should add a key for your value instead of passing it directly.

The third mistake is that queryParams should be sent as a second parameter to navigate, not as a second item in the routing array.

Here is the corrected code:

let params = {queryParams: {carrito: JSON.stringify(this.carrito)}};
this.router.navigate(['/carrito'], params);

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 issues with jsonConvert.deserializeObject not functioning in angular2 json2typescript

Greetings, I am new to Angular 2 and working on fetching user data from Google, Facebook, and LinkedIn. I am attempting to deserialize an object into an instance of a class I created named UserLogin, but unfortunately it does not seem to be working. Here ...

Is there a way to run a URL in Angular2 without having to include the ID like /edit/:id?

Looking to access a specific page in the browser? Instead of the longer URL below: You can use this shorter link to view or edit details for a specific ID in AngularJS 2. ...

After updating the state in a Reducer with Redux Toolkit, make sure to utilize a

Issue: Seeking efficient code writing methods. Here is a detailed example of my Redux Toolkit slice below: import { createSlice } from '@reduxjs/toolkit'; import { setCookie } from '../../utils/storageHandler'; const initialState = { ...

Launch another modal and then deactivate the initial modal

Having two Modals has presented a challenge for me when it comes to closing the first modal after the second one is opened. I attempted a solution, but it prevented the second Modal from opening altogether. This code snippet below belongs to the first Mo ...

Creating an app for sending text messages and making video calls with Spring Boot technology

I am interested in developing an application with Spring Boot that allows users to make video calls and share text messages. I also want the ability to save these videos for future viewing by registered users of the app. Although I am familiar with node.j ...

Examining form functionalities: angular2 form testing

Currently, I'm facing an issue while attempting to test a component that utilizes 'FormGroup' and 'FormBuilder'. Whenever I run the test file for this particular component, I encounter an error stating that 'FormGroup' an ...

Using type values in TypeScript

I am trying to assign interfaces as values within a config object: export interface RouterConfig { startEvents?: typeof RouterEvent[]; completeEvents?: typeof RouterEvent[]; } The intended usage is as follows: private config: RouterConfig = { star ...

Discovering Type Definitions in Nuxt.js Project Without Manual Imports in VSCode: A Step-by-Step Guide

Having issues with VSCode not recognizing type definitions automatically in a Nuxt.js project with TypeScript. I'm looking to avoid manually importing types in every file. Here's my setup and the problem I'm facing: Configuration My tsconfi ...

Most effective method for sending an HTTP Post request with a JSON body in Angular 9

Hi there, I'm currently working on a project that requires saving information from 3 text box fields. I've been struggling to figure out how to make a POST request with a JSON body. Here's what I have so far: I've been piecing together ...

Potential explanation for unexpected Typescript initialization error

I am encountering the compiler error The property 'options' is not initialized or assigned in the constructor. However, upon reviewing the code for the respective class, it is clear that this reported error does not accurately reflect the actual ...

Modify the database entry only if the user manually changes it, or temporarily pause specific subscriptions if the value is altered programmatically

After a change in the viewmodel, I want to immediately update the value on the server. class OrderLine { itemCode: KnockoutObservable<string>; itemName: KnockoutObservable<string>; constructor(code: string, name: string) { ...

Develop a JSON parsing function for VUE reusability

Currently, I am iterating through an array in Vue that contains objects with strings nested within. These objects have various properties such as idType, type, user, visibility, seller, product, company, and additionalData. notifications: [ 0: { idTy ...

Testing abstract class methods in Jest can ensure full coverage

In my project, I have an abstract generic service class. export default abstract class GenericService<Type> implements CrudService<Type> { private readonly modifiedUrl: URL; public constructor(url: string) { this.modifiedUrl = ...

Challenges encountered while setting up Hotjar integration in Next.js using Typescript

I am encountering issues with initializing hotjar in my Next.js and TypeScript application using react-hotjar version 6.0.0. The steps I have taken so far are: In the file _app.tsx I have imported it using import { hotjar } from 'react-hotjar' ...

What exactly happens behind the scenes when an API request is cancelled in an ASP .NET Core API?

Let's consider a scenario where we have a straightforward endpoint: [HttpGet] public async Task<ActionResult<string>> Get(CancellationToken cancellationToken) { // some logic here... } Now, imagine I make an HTTP request usi ...

Animation on React child component disappears when re-rendered

My React application utilizes Material UI with a component (let's call it DateSelector) as shown below, slightly altered for demonstration purposes. https://i.sstatic.net/RlPZa.gif Material UI provides animations for clicks and interactions within i ...

Error encountered during Angular upload using Asp.net core: System.Text.DecoderFallbackException is thrown when bytes [FF] cannot be translated at the specified index

I am having trouble uploading a file using Angular 7 and Asp.net core 2.2 I have set up the Angular web service to append the file and include a property Name. However, when I call the WebService from Angular, I encounter an error in the Asp.net core l ...

Troubleshooting a pair of distinct software programs: Angular and a web API

I am currently working on two separate applications, one developed in Angular and the other in web API. There is a function in my Angular application that calls a method in .NET Core. I would like to know if it is possible to debug the Angular function and ...

What is the best approach when one property of a typescript class relies on the values of two others?

Currently, I have a TypeScript class within an Angular application that consists of three properties. The first two properties can be changed independently using [(ngModel)]. However, I am looking for a way to set the third property as the sum of the first ...

Is Angular 2+ responsible for loading the entire module or only the exported components within it?

I'm dealing with a situation where I have a large module but only need to export one specific component. I'm wondering if Angular loads the entire module or just the exported components, as I want to optimize performance without compromising the ...