update values in react form input fields












0















I am new to react and I can fetch the result from form input fields. Now I need to update those values and submit to the backend. I am struggling to find a way to pass all the input field values at once.



constructor(props) {
super(props);
this.state = {
items: ,
isLoaded: false,
data: this.props.location.data
};
}

render() {
return (
<div>
<h2>Update Your Profile</h2>
{items.map(item => (
<Form key={item.uId} onSubmit={this.handleSubmit}>
<label>User Name</label>
<input type="text" defaultValue={item.userName}></input>
<label>Email address</label>
<input type="email" defaultValue={item.email}></input>
</div>
<button type="submit" >Update</button>
</Form>
))}
</div>
);
}

handleSubmit = (e) => {
e.preventDefault();
axios.put('http://localhost:3000/api/user/' + this.state.data, this.state.items).then(response => {
//
});
};


My API call looks like this:



app.put('/api/user/:userId', (req, res, err) => {
User.update(
{ userName: req.body.userName, email: req.body.email },
{
where: {
userId: req.params.userId
}
}
).then(function (rowsUpdated) {
res.json(rowsUpdated)
}).catch(err);
});


How can I modify this code to set a value for this.state.items with all the updated fields values and submit it?










share|improve this question

























  • What does your API expect for the PUT? What properties/structure does it expect? Try JSON.stringify() on your body.

    – Alexander Staroselsky
    Dec 30 '18 at 17:19











  • updated the question with api

    – M.Cooper
    Dec 30 '18 at 17:24











  • Your API endpoint seems to expect a single username and email, but you are trying to send an array of these values. There are a couple things you’d need to handle first, a mechanism for updating the input values for a given array item and a way to handle those individually for each respective submit. If you put the form part into a sub component you will be able to do that easily.

    – Alexander Staroselsky
    Dec 30 '18 at 17:41
















0















I am new to react and I can fetch the result from form input fields. Now I need to update those values and submit to the backend. I am struggling to find a way to pass all the input field values at once.



constructor(props) {
super(props);
this.state = {
items: ,
isLoaded: false,
data: this.props.location.data
};
}

render() {
return (
<div>
<h2>Update Your Profile</h2>
{items.map(item => (
<Form key={item.uId} onSubmit={this.handleSubmit}>
<label>User Name</label>
<input type="text" defaultValue={item.userName}></input>
<label>Email address</label>
<input type="email" defaultValue={item.email}></input>
</div>
<button type="submit" >Update</button>
</Form>
))}
</div>
);
}

handleSubmit = (e) => {
e.preventDefault();
axios.put('http://localhost:3000/api/user/' + this.state.data, this.state.items).then(response => {
//
});
};


My API call looks like this:



app.put('/api/user/:userId', (req, res, err) => {
User.update(
{ userName: req.body.userName, email: req.body.email },
{
where: {
userId: req.params.userId
}
}
).then(function (rowsUpdated) {
res.json(rowsUpdated)
}).catch(err);
});


How can I modify this code to set a value for this.state.items with all the updated fields values and submit it?










share|improve this question

























  • What does your API expect for the PUT? What properties/structure does it expect? Try JSON.stringify() on your body.

    – Alexander Staroselsky
    Dec 30 '18 at 17:19











  • updated the question with api

    – M.Cooper
    Dec 30 '18 at 17:24











  • Your API endpoint seems to expect a single username and email, but you are trying to send an array of these values. There are a couple things you’d need to handle first, a mechanism for updating the input values for a given array item and a way to handle those individually for each respective submit. If you put the form part into a sub component you will be able to do that easily.

    – Alexander Staroselsky
    Dec 30 '18 at 17:41














0












0








0








I am new to react and I can fetch the result from form input fields. Now I need to update those values and submit to the backend. I am struggling to find a way to pass all the input field values at once.



constructor(props) {
super(props);
this.state = {
items: ,
isLoaded: false,
data: this.props.location.data
};
}

render() {
return (
<div>
<h2>Update Your Profile</h2>
{items.map(item => (
<Form key={item.uId} onSubmit={this.handleSubmit}>
<label>User Name</label>
<input type="text" defaultValue={item.userName}></input>
<label>Email address</label>
<input type="email" defaultValue={item.email}></input>
</div>
<button type="submit" >Update</button>
</Form>
))}
</div>
);
}

handleSubmit = (e) => {
e.preventDefault();
axios.put('http://localhost:3000/api/user/' + this.state.data, this.state.items).then(response => {
//
});
};


My API call looks like this:



app.put('/api/user/:userId', (req, res, err) => {
User.update(
{ userName: req.body.userName, email: req.body.email },
{
where: {
userId: req.params.userId
}
}
).then(function (rowsUpdated) {
res.json(rowsUpdated)
}).catch(err);
});


How can I modify this code to set a value for this.state.items with all the updated fields values and submit it?










share|improve this question
















I am new to react and I can fetch the result from form input fields. Now I need to update those values and submit to the backend. I am struggling to find a way to pass all the input field values at once.



constructor(props) {
super(props);
this.state = {
items: ,
isLoaded: false,
data: this.props.location.data
};
}

render() {
return (
<div>
<h2>Update Your Profile</h2>
{items.map(item => (
<Form key={item.uId} onSubmit={this.handleSubmit}>
<label>User Name</label>
<input type="text" defaultValue={item.userName}></input>
<label>Email address</label>
<input type="email" defaultValue={item.email}></input>
</div>
<button type="submit" >Update</button>
</Form>
))}
</div>
);
}

handleSubmit = (e) => {
e.preventDefault();
axios.put('http://localhost:3000/api/user/' + this.state.data, this.state.items).then(response => {
//
});
};


My API call looks like this:



app.put('/api/user/:userId', (req, res, err) => {
User.update(
{ userName: req.body.userName, email: req.body.email },
{
where: {
userId: req.params.userId
}
}
).then(function (rowsUpdated) {
res.json(rowsUpdated)
}).catch(err);
});


How can I modify this code to set a value for this.state.items with all the updated fields values and submit it?







reactjs






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 30 '18 at 17:28









MTCoster

3,27122040




3,27122040










asked Dec 30 '18 at 17:13









M.CooperM.Cooper

327




327













  • What does your API expect for the PUT? What properties/structure does it expect? Try JSON.stringify() on your body.

    – Alexander Staroselsky
    Dec 30 '18 at 17:19











  • updated the question with api

    – M.Cooper
    Dec 30 '18 at 17:24











  • Your API endpoint seems to expect a single username and email, but you are trying to send an array of these values. There are a couple things you’d need to handle first, a mechanism for updating the input values for a given array item and a way to handle those individually for each respective submit. If you put the form part into a sub component you will be able to do that easily.

    – Alexander Staroselsky
    Dec 30 '18 at 17:41



















  • What does your API expect for the PUT? What properties/structure does it expect? Try JSON.stringify() on your body.

    – Alexander Staroselsky
    Dec 30 '18 at 17:19











  • updated the question with api

    – M.Cooper
    Dec 30 '18 at 17:24











  • Your API endpoint seems to expect a single username and email, but you are trying to send an array of these values. There are a couple things you’d need to handle first, a mechanism for updating the input values for a given array item and a way to handle those individually for each respective submit. If you put the form part into a sub component you will be able to do that easily.

    – Alexander Staroselsky
    Dec 30 '18 at 17:41

















What does your API expect for the PUT? What properties/structure does it expect? Try JSON.stringify() on your body.

– Alexander Staroselsky
Dec 30 '18 at 17:19





What does your API expect for the PUT? What properties/structure does it expect? Try JSON.stringify() on your body.

– Alexander Staroselsky
Dec 30 '18 at 17:19













updated the question with api

– M.Cooper
Dec 30 '18 at 17:24





updated the question with api

– M.Cooper
Dec 30 '18 at 17:24













Your API endpoint seems to expect a single username and email, but you are trying to send an array of these values. There are a couple things you’d need to handle first, a mechanism for updating the input values for a given array item and a way to handle those individually for each respective submit. If you put the form part into a sub component you will be able to do that easily.

– Alexander Staroselsky
Dec 30 '18 at 17:41





Your API endpoint seems to expect a single username and email, but you are trying to send an array of these values. There are a couple things you’d need to handle first, a mechanism for updating the input values for a given array item and a way to handle those individually for each respective submit. If you put the form part into a sub component you will be able to do that easily.

– Alexander Staroselsky
Dec 30 '18 at 17:41












1 Answer
1






active

oldest

votes


















0














I'd recommend to create a new component to wrap around the <Form /> and move the submit/change event handling to that component for each item. This would allow you to be able to extract individual email/userName for any given <Form /> to send as a PUT to your API endpoint as well as handle the respective input value changes.



Parent Component:



class Parent extends Component {
constructor() {
super();
this.state = {
name: 'React',
items: [
{ uId: 1, email: 'foo@test.com', userName: 'bar' },
{ uId: 2, email: 'baz@test.com', userName: 'foobar' }
]
};
}

render() {
return (
<div>
{this.state.items.map(item =>
<MyForm key={item.uId} item={item} data={this.props.location.data} />)}
</div>
);
}
}


Child/Form Component:



import React, { Component } from 'react';

class MyForm extends Component {
constructor(props) {
super(props);

this.state = {
email: this.props.item.email,
userName: this.props.item.userName
};

this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}

// https://reactjs.org/docs/forms.html#handling-multiple-inputs
handleChange(e) {
const { target} = event;
const value = target.type === 'checkbox' ? target.checked : target.value;
const { name } = target;

this.setState({ [name]: value });
}

handleSubmit(e) {
e.preventDefault();

const { email, userName } = this.state;
const body = { email, userName };
const json = JSON.stringify(body);
console.log(json);

// axios.put('http://localhost:3000/api/user/' + this.props.data, json).then(response => {});
}

render() {
return (
<form onSubmit={this.handleSubmit}>
<label>User Name</label>
<input type="text" defaultValue={this.state.userName}></input>
<label>Email address</label>
<input type="email" defaultValue={this.state.email}></input>

<button type="submit" >Update</button>
</form>
);
}
}

export default MyForm;


Here is an example in action.



Hopefully that helps!






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53979743%2fupdate-values-in-react-form-input-fields%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    I'd recommend to create a new component to wrap around the <Form /> and move the submit/change event handling to that component for each item. This would allow you to be able to extract individual email/userName for any given <Form /> to send as a PUT to your API endpoint as well as handle the respective input value changes.



    Parent Component:



    class Parent extends Component {
    constructor() {
    super();
    this.state = {
    name: 'React',
    items: [
    { uId: 1, email: 'foo@test.com', userName: 'bar' },
    { uId: 2, email: 'baz@test.com', userName: 'foobar' }
    ]
    };
    }

    render() {
    return (
    <div>
    {this.state.items.map(item =>
    <MyForm key={item.uId} item={item} data={this.props.location.data} />)}
    </div>
    );
    }
    }


    Child/Form Component:



    import React, { Component } from 'react';

    class MyForm extends Component {
    constructor(props) {
    super(props);

    this.state = {
    email: this.props.item.email,
    userName: this.props.item.userName
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    }

    // https://reactjs.org/docs/forms.html#handling-multiple-inputs
    handleChange(e) {
    const { target} = event;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const { name } = target;

    this.setState({ [name]: value });
    }

    handleSubmit(e) {
    e.preventDefault();

    const { email, userName } = this.state;
    const body = { email, userName };
    const json = JSON.stringify(body);
    console.log(json);

    // axios.put('http://localhost:3000/api/user/' + this.props.data, json).then(response => {});
    }

    render() {
    return (
    <form onSubmit={this.handleSubmit}>
    <label>User Name</label>
    <input type="text" defaultValue={this.state.userName}></input>
    <label>Email address</label>
    <input type="email" defaultValue={this.state.email}></input>

    <button type="submit" >Update</button>
    </form>
    );
    }
    }

    export default MyForm;


    Here is an example in action.



    Hopefully that helps!






    share|improve this answer






























      0














      I'd recommend to create a new component to wrap around the <Form /> and move the submit/change event handling to that component for each item. This would allow you to be able to extract individual email/userName for any given <Form /> to send as a PUT to your API endpoint as well as handle the respective input value changes.



      Parent Component:



      class Parent extends Component {
      constructor() {
      super();
      this.state = {
      name: 'React',
      items: [
      { uId: 1, email: 'foo@test.com', userName: 'bar' },
      { uId: 2, email: 'baz@test.com', userName: 'foobar' }
      ]
      };
      }

      render() {
      return (
      <div>
      {this.state.items.map(item =>
      <MyForm key={item.uId} item={item} data={this.props.location.data} />)}
      </div>
      );
      }
      }


      Child/Form Component:



      import React, { Component } from 'react';

      class MyForm extends Component {
      constructor(props) {
      super(props);

      this.state = {
      email: this.props.item.email,
      userName: this.props.item.userName
      };

      this.handleChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
      }

      // https://reactjs.org/docs/forms.html#handling-multiple-inputs
      handleChange(e) {
      const { target} = event;
      const value = target.type === 'checkbox' ? target.checked : target.value;
      const { name } = target;

      this.setState({ [name]: value });
      }

      handleSubmit(e) {
      e.preventDefault();

      const { email, userName } = this.state;
      const body = { email, userName };
      const json = JSON.stringify(body);
      console.log(json);

      // axios.put('http://localhost:3000/api/user/' + this.props.data, json).then(response => {});
      }

      render() {
      return (
      <form onSubmit={this.handleSubmit}>
      <label>User Name</label>
      <input type="text" defaultValue={this.state.userName}></input>
      <label>Email address</label>
      <input type="email" defaultValue={this.state.email}></input>

      <button type="submit" >Update</button>
      </form>
      );
      }
      }

      export default MyForm;


      Here is an example in action.



      Hopefully that helps!






      share|improve this answer




























        0












        0








        0







        I'd recommend to create a new component to wrap around the <Form /> and move the submit/change event handling to that component for each item. This would allow you to be able to extract individual email/userName for any given <Form /> to send as a PUT to your API endpoint as well as handle the respective input value changes.



        Parent Component:



        class Parent extends Component {
        constructor() {
        super();
        this.state = {
        name: 'React',
        items: [
        { uId: 1, email: 'foo@test.com', userName: 'bar' },
        { uId: 2, email: 'baz@test.com', userName: 'foobar' }
        ]
        };
        }

        render() {
        return (
        <div>
        {this.state.items.map(item =>
        <MyForm key={item.uId} item={item} data={this.props.location.data} />)}
        </div>
        );
        }
        }


        Child/Form Component:



        import React, { Component } from 'react';

        class MyForm extends Component {
        constructor(props) {
        super(props);

        this.state = {
        email: this.props.item.email,
        userName: this.props.item.userName
        };

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        }

        // https://reactjs.org/docs/forms.html#handling-multiple-inputs
        handleChange(e) {
        const { target} = event;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const { name } = target;

        this.setState({ [name]: value });
        }

        handleSubmit(e) {
        e.preventDefault();

        const { email, userName } = this.state;
        const body = { email, userName };
        const json = JSON.stringify(body);
        console.log(json);

        // axios.put('http://localhost:3000/api/user/' + this.props.data, json).then(response => {});
        }

        render() {
        return (
        <form onSubmit={this.handleSubmit}>
        <label>User Name</label>
        <input type="text" defaultValue={this.state.userName}></input>
        <label>Email address</label>
        <input type="email" defaultValue={this.state.email}></input>

        <button type="submit" >Update</button>
        </form>
        );
        }
        }

        export default MyForm;


        Here is an example in action.



        Hopefully that helps!






        share|improve this answer















        I'd recommend to create a new component to wrap around the <Form /> and move the submit/change event handling to that component for each item. This would allow you to be able to extract individual email/userName for any given <Form /> to send as a PUT to your API endpoint as well as handle the respective input value changes.



        Parent Component:



        class Parent extends Component {
        constructor() {
        super();
        this.state = {
        name: 'React',
        items: [
        { uId: 1, email: 'foo@test.com', userName: 'bar' },
        { uId: 2, email: 'baz@test.com', userName: 'foobar' }
        ]
        };
        }

        render() {
        return (
        <div>
        {this.state.items.map(item =>
        <MyForm key={item.uId} item={item} data={this.props.location.data} />)}
        </div>
        );
        }
        }


        Child/Form Component:



        import React, { Component } from 'react';

        class MyForm extends Component {
        constructor(props) {
        super(props);

        this.state = {
        email: this.props.item.email,
        userName: this.props.item.userName
        };

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        }

        // https://reactjs.org/docs/forms.html#handling-multiple-inputs
        handleChange(e) {
        const { target} = event;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const { name } = target;

        this.setState({ [name]: value });
        }

        handleSubmit(e) {
        e.preventDefault();

        const { email, userName } = this.state;
        const body = { email, userName };
        const json = JSON.stringify(body);
        console.log(json);

        // axios.put('http://localhost:3000/api/user/' + this.props.data, json).then(response => {});
        }

        render() {
        return (
        <form onSubmit={this.handleSubmit}>
        <label>User Name</label>
        <input type="text" defaultValue={this.state.userName}></input>
        <label>Email address</label>
        <input type="email" defaultValue={this.state.email}></input>

        <button type="submit" >Update</button>
        </form>
        );
        }
        }

        export default MyForm;


        Here is an example in action.



        Hopefully that helps!







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Dec 30 '18 at 18:23

























        answered Dec 30 '18 at 18:07









        Alexander StaroselskyAlexander Staroselsky

        12.3k42040




        12.3k42040






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53979743%2fupdate-values-in-react-form-input-fields%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Monofisismo

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas