Encountering a cloning error while using React Typescript and React Router DOM when calling props.history.push

When using props.history.push without passing state, everything works perfectly fine. However, when trying to pass data with state, an error occurs. The error message reads: DOMException: Failed to execute 'pushState' on 'History': function transformRequest(data, headers) {normalizeHeaderName(headers, 'Accept');normalizeHeaderName(...... } could not be cloned.at globalHistory.pushState. I am getting the following error: history.js:357 Uncaught (in promise) My Code is;

import axios from 'axios';
import React from 'react';
import { RouteComponentProps, withRouter  } from 'react-router-dom';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import Box from '@mui/material/Box';
import FormGroup from '@mui/material/FormGroup';
import Select from '@mui/material/Select';

 interface WeatherDataCredentials {
  StationName?: string,
  StartDay?: string,
  EndDay?: string
 }
 class SearchData extends React.Component<RouteComponentProps, WeatherDataCredentials> {
   constructor(props: RouteComponentProps) {
     super(props)

    this.state = {
    StationName: '',
    StartDay: '',
    EndDay: ''
   }    
    
   } 

  onButtonClick = async (event: React.FormEvent) => {
  event.preventDefault();
  await axios.post('http://localhost:4000/api/weatherData',
    {        
        StationName: this.state.StationName,            
        StartDay: this.state.StartDay,
        EndDay: this.state.EndDay          
    })
    .then(data => {
      console.log('Props', this.props)          
         this.props.history.push({
        pathname: '/data',
        state:
        {
            data:data
        }
        });  
          
    }          
    )    
    }
  render() {
  
   return (
   <Box
    component="form"
    sx={{
      '& .MuiTextField-root': { m: 1, width: '25ch' },
    }}
    noValidate
    autoComplete="off"
  >
    <div>
      <h3>Weather Data Search</h3>
            <FormGroup >
                <InputLabel id="demo-simple-select-label">Station Name</InputLabel>
  <Select    
value={this.state.StationName}
label="Station Name"
onChange={(event) => this.setState({              
            StationName: event.target.value                
          })}
 >
<MenuItem value="Buche">Buche</MenuItem>

</Select>

        <TextField              
          required              
          label="StartDay"              
          type="text"          
          value={this.state.StartDay}              
          onChange={(event) => this.setState({              
            StartDay: event.target.value                
          })}              
                />
                <TextField              
          required              
          label="StartDay"              
          type="text"          
          value={this.state.EndDay}              
          onChange={(event) => this.setState({              
            EndDay: event.target.value                
          })}              
        />
        <Button onClick={this.onButtonClick} variant='contained' color='primary'>Search 
     Data</Button> 
      </FormGroup>
    </div>        
  </Box>      
   )
   }  
 }

 export default withRouter(SearchData)

Answer №1

When working with router state, it's important to note that the state must be clonable. However, the axios response object (referred to as data, even though this may be a misleading name) is not clonable due to the presence of functions within it.

I suggest selecting only the necessary values and creating the state using those values, rather than including the entire response object. For instance, if you only require the response data:

onButtonClick = async (event: React.FormEvent) => {
  event.preventDefault();
  const reply = await axios.post("http://localhost:4000/api/weatherData", {
    StationName: this.state.StationName,
    StartDay: this.state.StartDay,
    EndDay: this.state.EndDay,
  });
  this.props.history.push({
    pathname: "/data",
    state: {
      data: reply.data,
    },
  });
};

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

What is the best way to align a modal with a layout when it appears far down the components hierarchy?

Struggling with creating a React modal and facing some issues. Let's consider the structure below: React structure <ComponentUsingModal> <Left> <ButtonToActivateModal> ... </ButtonToActivateModa ...

Tips for showing items on the screen with a search text input in Expo and React Native

Utilizing react native and expo, I have JSON data presented on the iOS simulator screen that was fetched from an API. Positioned at the top is a search bar where users can query the displayed data. For instance, if the data appears as follows: A a compa ...

Transforming three items into an array with multiple dimensions

There are 3 unique objects that hold data regarding SVG icons from FontAwesome. Each object follows the same structure, but the key difference lies in the value of the prefix property. The first object utilizes fab as its prefix, the second uses far, and t ...

The files _buildmanifest.js and _ssgmanifest.js could not be loaded. The server returned a 404 error, indicating that the resources were not found

Upcoming: 12.3.4 React Version: 17.0.2 Node Version: 16.13.1 An error is persisting in my Next.js application where the console displays the following message on all pages I load: 404 Failed to load resource: the server responded with a status of 404 ( ...

Typescript: require generic types to include specific keys at all times

Is there a way to ensure that the function below only accepts a data object if it contains an id key, and then allows us to access the id from the data object? function someFuntion<T>(data : T){ const id = data['id'] //Error : Element imp ...

What is the best way to effectively nest components with the Nebular UI Kit?

I'm currently facing an issue with nesting Nebular UI Kit components within my Angular app. Specifically, I am trying to nest a header component inside the home page component. The problem arises when the attributes take up the entire page by default, ...

Unsuitable data types in GraphQL - is the configuration faulty?

I'm currently facing an issue that's giving me some trouble. In my datamodel.prisma, I added a new type called Challenge: type Challenge { id: ID! @id createdAt: DateTime! @createdAt updatedAt: DateTime! @updatedAt completed: Bo ...

Generate an array that can be accessed across all components

As someone new to reactjs, I'm trying to figure out how to handle an array of objects so that it can be global and accessed from multiple components. Should I create another class and import it for this purpose? In Angular, I would typically create a ...

Validating Inputs with an Array of Values in my Angular 2 Application

I have been exploring ways to retrieve data from an array of values instead of a single value when using [(ngModel)] binding in my Angular 2 application. The current setup functions perfectly with a single value, as shown below. The data is pulled from the ...

Combining the Express.js API with React to create an interactive data visualization using CanvasJS

After developing an api in node.js that provides data in json format, I am looking to utilize this data for visualization purposes. To demonstrate this, I have prepared a sample of data visualization using canvasjs within React. class BarChart extends Com ...

To properly render JSX elements in ReactJS, make sure to enclose adjacent elements within a wrapping tag. If you prefer to use a

Hey, I just started learning React and decided to create a blog. The blog elements are stored in an array and I'm using a map function to display the blog posts. However, when I add something to the map function, I encountered this error: Adjacent JSX ...

Comparison between Template Engines and ReactJs

Looking for advice on templating engines and ReactJs. Although I'm new to web development, I'm eager to learn. Can React be used as the sole templating engine to render server-side pages? Any assistance would be greatly appreciated. Thank you. ...

What are the steps to rectify the issue of displaying data accurately on

I am working on my ReactJS project and using devextreme to create a unique circular gauge. However, I'm facing an issue where certain values are not being displayed correctly. For instance, instead of showing the value 5011480286.78, it is displaying ...

New Requirement for Angular Service: Subclass Constructor Must Be Provided or Unable to Resolve all Parameters for ClassName (?)

During a recent project, I encountered an issue while working on several services that all extend a base Service class. The base class requires a constructor parameter of HttpClient. When setting up the subclass with autocomplete, I noticed that their con ...

I need to sort my tags by comma and use MUI Select to filter them

[ {id: 'AjRzfMxbfJMphK144DIAr', title: 'javascript', tags: 'code,programining', notes: "This book is a must to", createdAt: 1671459053853} {id: 'kvdo7HrLr2GeOUX9j4qLq', title: 'css', tags: &ap ...

Add integer to an array of strings

Currently, I am utilizing an autocomplete feature and aiming to save the IDs of the selected users. My goal is to store these IDs in a string array, ensuring that all values are unique with no duplicates. I have attempted to push and convert the values u ...

Tips for customizing the appearance of a label when a MUI Radio Button is selected

Hello everyone, I am attempting to customize the label text color of a radio button to turn blue when selected. https://i.stack.imgur.com/btSc2.jpg HERE IS THE CODE FOR MY MUI BUTTON SO FAR import * as React from "react"; import Radio from &quo ...

Is it possible to utilize an XML format for translation files instead of JSON in React Native?

I'm in the process of creating a react native application using the react i18next library. For translations, I've utilized XML format in android for native development. In react native, is it possible to use XML format for translation files inste ...

Load a script in a specific div using React

Can anyone assist me with loading a script onto a specific component in my React application? Here is the script that needs to be loaded at the bottom-most div within my component: <div id="rexxxx"></div> <script> new carouselI ...

It is not always a guarantee that all promises in typescript will be resolved completely

I have a requirement in my code to update the model data { "customerCode": "CUS15168", "customerName": "Adam Jenie", "customerType": "Cash", "printPackingSlip": "true", "contacts": [ { "firstName": "Hunt", "lastName": "Barlow", ...