0

I have value that i want to update and send an update post request , so i tried this:

EDIT

i add more code that represenet the all component:

import React from 'react'
import axios from 'axios'
import {Card} from 'react-bootstrap'
 class SubmitPage extends React.Component{
    constructor(props) {
    super(props)
    this.state={formname:'',
                fields:[''],
                values:[''],
                submissions:0
                }
    }


    handleChange=this.handleChange.bind(this)
    saveChanges=this.saveChanges.bind(this)
    componentDidMount=this.componentDidMount.bind(this)


    //get the Object from DB and initialize new state
    componentDidMount()
    {
    axios.get('http://localhost:2000/form/'+this.props.match.params.id).then(response =>{
        this.setState({
            formname:response.data.formname,
            fields:response.data.fields,
            submissions:response.data.submissions
            })
         })
      .catch(function(error){
        })
    }

    handleChange(e,index)
    {
        this.setState({
            values: {
               ...this.state.values,
               [index.index]: e.target.value
            }
          });
    }
    async saveChanges(e)
    {
        e.preventDefault();
        //update the values in field array
        const {values}=this.state;
        const fields=this.state.fields;
        Object.keys(values).map(key => 
            fields[key].push(values[key])
        )
        //get submission and update it
        axios.get('http://localhost:2000/form/'+this.props.match.params.id)
        .then(response =>{
            this.setState({
            submissions: response.data.submissions
            })
            console.log(this.state.submissions)
         })
         .catch(function(error){
             console.log(error);
         })

         //let submissionsUpdate=this.state.submissions;
       //  submissionsUpdate=submissionsUpdate+1;                                  
       this.setState({
           submissions: this.state.submissions+1}, ()=> { 
            const form={
                formname:this.state.formname,
                fields:this.state.fields,
                submissions: this.state.submissions
            }
        axios.post('http://localhost:2000/form/update/'+this.props.match.params.id,form)  //post after sumbmission value update
        .then(res => console.log(res.data));

        });
        window.location='/'
    }
    render(){
        const {fields}=this.state
        return(
        <div  style={{width:'35%' , margin:"0 auto" ,marginTop:"3%"}}>
        <Card >
        <Card.Header as="h5">{this.state.formname}</Card.Header>
        <Card.Body>
        <Card.Text>
        <div>{fields.length!==0&&fields.map((fields,index)=> {
                    return (
                        <div key={fields[0]}>
                            <div style={{fontSize:'15px' , marginBottom:"-1px"}}>{fields[0]}</div>
                            <div><input onChange={(e) => this.handleChange(e, {index})} type={fields[1]}></input></div>
                        </div>
                            )
                        }) 
                    } 
                    </div>
       <button style={{width:100, marginTop:"10px", marginBottom:"20px"}}  type="submit" onClick={this.saveChanges} className="btn btn-dark"> Submit</button>

        </Card.Text>
        </Card.Body>
      </Card>
      </div>)
        }
    }

export default SubmitPage

my goal is to increase counter by 1 , but because the setState is asych, something goes wrong , and the result is or increasing by strange number or no change. what i am doing wrong?

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
David
  • 11
  • 2
  • 1
    setState is async, so if you need to wait for a state update, you'll have to literally do that: `setState( { new values }, () => { code to run after state is updated })`. Or possibly even better, put your "to do after state gets updated" code in the [componentDidUpdate()](https://reactjs.org/docs/react-component.html#componentdidupdate) lifecycle function – Mike 'Pomax' Kamermans Mar 03 '20 at 19:40
  • Also, `fields[key].push(values[key])` is mutating the current state which is an anti-pattern in React. – Emile Bergeron Mar 03 '20 at 19:48
  • 2
    Does this answer your question? [Why calling react setState method doesn't mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-calling-react-setstate-method-doesnt-mutate-the-state-immediately) – Emile Bergeron Mar 03 '20 at 19:49
  • i tried to do all in the setState callback function , but its still not working well :( – David Mar 03 '20 at 20:05
  • It would be helpful if you would edit your post to add what you tried to do based off the above comments, that way they can review if what you did was the correct interpretation of their solution. – canpan14 Mar 03 '20 at 20:26
  • @canpan14 done. – David Mar 03 '20 at 20:54
  • What current issue are you facing after changing that? Note it's still all async, so the rest of the code/rendering will keep on occurring. That change just fixed it so that the form/network call don't fire off until the state is updated. – canpan14 Mar 03 '20 at 21:12

0 Answers0