1

I am new in react. I write react with typescript without redux. In my sample project i want after submit form, change route, but i can not do this. following code is my try. how can I change route in fetch then function? why this value is undefined!

import * as React from 'react';
import 'isomorphic-fetch';
import { ReactRouter } from 'react-router-dom';

export interface Props {router?: ReactRouter.History.History;}

interface State {name: string;}

export class CreateItem extends React.Component<Props, State> {

    private input: HTMLInputElement;

    constructor(props: Props) {

        super(props);

        this.state = {name: ""};

        this.input = null;
    }

    public render(){

        return <form onSubmit={this.handleSubmit} className="form-horizontal">
            <div className="form-group">
                <label className="col-sm-2 control-label">Date</label>
                <div className="col-sm-5">
                    <input name="name" type="text" value={this.state.name} onChange={this.handleInputChange} className="form-control">
                    </input>
                </div>
            </div>

            <div className="form-group">
                <div className="col-sm-offset-2 col-sm-5">
                    <button type="submit" className="btn btn-default" disabled={!this.state.name}>ADD</button>
                </div>
            </div>
        </form>;
    }

    private handleSubmit = (event: React.FormEvent<HTMLFormElement>): void => {

        event.preventDefault();

        if (this.state.name) {

            var form = new FormData();

            form.append('name', name);

            fetch('/api/SampleData/', { method: 'POST', body: form })
                .then(function (res) {
                    this.props.history.push('/fetchdata');// **this code not work**
                });

            this.setState({
                name: ""
            });
        }
    }

    private handleInputChange = (event: React.FormEvent<HTMLInputElement>): void => {

        const target = event.target;
        const name = target["name"];

        this.setState({
            [name]: (event as any).target.value
        })
    }
}
Mohammad Akbari
  • 4,486
  • 6
  • 43
  • 74

2 Answers2

1

It's probably late but anyway. Try to use the arrow function to get correct this

.then(res => {
  this.props.history.push('/fetchdata');
});
marksman
  • 68
  • 6
  • I used your suggested code but throw this error TS2339: Property 'history' does not exist on type 'Readonly<{ children?: ReactNode; }> & Readonly' – Mohammad Akbari Jul 24 '17 at 04:41
  • 1
    @MohammadAkbari the `history` property is absent cause you probably use the 'react-router' in a wrong way. Please check this [link](https://stackoverflow.com/questions/31079081/programmatically-navigate-using-react-router) – marksman Aug 02 '17 at 13:32
0

You are using the React Router in the wrong way. Here it is, how using it.

styles comes from MaterialUI.

const styles = (theme: Theme) =>
  createStyles
  ({})

interface IState
{}

interface IProps
{}

class Home extends React.Component<IProps & WithStyles<typeof styles> & RouteComponentProps<{}>, IState>
{   
    constructor(props: IProps & WithStyles<typeof styles> & RouteComponentProps<{}>)
    {
        super(props);

        this.state =
        {
        }
    }
}

to navigate use: this.props.history.push(your route goes here);

Wasyster
  • 2,279
  • 4
  • 26
  • 58