Neff
Neff

Reputation: 189

Set input value automatically on a fetch request

I present my problem to you

In the following code, I'm trying to retrieve phone numbers from an API and then show them in a Card; in each card, I have a different number which is displayed

and also in each card, I have an input field to enter the phone number which I obtained before.

My problem is that I don't want to fill in the input manually with the recovered number.

So basically I would like to start my function without having to fill in this field manually.

Do you have any idea how to do this? I tried to simplify the code so that it is as clear as possible Thanks for your help Neff

 import React, { Component } from 'react';
 import { CardText, Card,Row, Col, CardTitle, Button } from 'reactstrap';
 import axios from 'axios'

 const entrypoint = process.env.REACT_APP_API_ENTRYPOINT+'/api';

 class AdminPage  extends Component {


constructor(props) {
    super(props);
    this.state = {
        data: [],
        message: {
            to: '',
            body: 'hola amigo :)'
          },
          submitting: false,
          error: false
    };
    this.onHandleChange = this.onHandleChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);

}

onSubmit(event) {
    event.preventDefault();
    this.setState({ submitting: true });
    fetch('/api/messages', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(this.state.message)
    })
      .then(res => res.json())
      .then(data => {
        if (data.success) {
          this.setState({
            error: false,
            submitting: false,
            message: {
              to: '',
              body: ''
            }
          });
        } else {
          this.setState({
            error: true,
            submitting: false
          });
        }
      });
   }
   // rest of the component
    onHandleChange(event) {
    const name = event.target.getAttribute('name');
    this.setState({
      message: { ...this.state.message, [name]: event.target.value }
    });
  }
getRandom = async () => {

    const res = await axios.get(
        entrypoint + "/alluserpls"
    )
    this.setState({ data: res.data })
}
componentDidMount() {
    this.getRandom()
}
render() {

    let datas = this.state.data.map(datass => {
       const status = JSON.parse(localStorage.getItem("validated-order")||"{}")[datass.id];
        return (
            <div>
              < Col sm="12" key={datass.id} className="wtfFuHereIsForOnlyBackGroundColorForCol12Nice">

           <div key="a"> 
      <Card body className="yoloCardBody">

      <CardText> Téléphone {datass.phone}</CardText>

     <form
    onSubmit={this.onSubmit}
    className={this.state.error ? 'error sms-form' : 'sms-form'}  >
        <div>
          <input
             type="tel"
             name="to"
             id="to"
             value={this.state.message.to}
        onChange={this.onHandleChange}
        /> 
        </div> 
      <Button className="buttonForLancerMaybe" type="submit" disabled= 
      {this.state.submitting}>SMS</Button>
      </form>
    </Card>
    </div>
  </Col>
            </div>
        )
    })
    return (
        <div> <div>
    <div> 
    {datas}
  </div>
    </div>
    </div>
            <div className="box">       
            </div>
        </div>
    )
    }
    }

 export default AdminPage 

Upvotes: 1

Views: 1424

Answers (1)

BlackSheep
BlackSheep

Reputation: 613

So I guess this little change in your code will help you, separating the logic and making a new component for your form section would be your solution. say we have a component called "SmsForm" so first, you need to import it in your current component:

import SmsForm from "../SmsForm/Loadable";

and then you pass your phone number as a prop to this SmsForm like this:

let datas = this.state.data.map(datass => {
    const status = JSON.parse(localStorage.getItem("validated-order") || "{}")[datass.id];
    return (
        <div>
            < Col sm="12" key={datass.id} className="wtfFuHereIsForOnlyBackGroundColorForCol12Nice">

                <GridLayout className="GridlayoutTextOnlyForGridOuiAndHeigthbecauseHeigthWasBug" layout={layout} cols={12} rowHeight={30} width={1200}>

                    <div key="a">
                        <Card body className="yoloCardBody">

                            <CardText> Téléphone {datass.phone}</CardText>

                           <SmsForm phone={datass.phone}/>
                        </Card>
                    </div>
                </GridLayout>
            </ Col>
        </div>
    )
})

and SmsForm would be sth like this:

    import React from 'react';
     ...
    export class SmsForm extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                message: {
                    to: props.phone,
                    body: 'hola amigo :)'
                },
                submitting: false,
                error: false
            };
            this.onHandleChange = this.onHandleChange.bind(this);
            this.onSubmit = this.onSubmit.bind(this);
        }


        onSubmit(event) {
            event.preventDefault();
            this.setState({ submitting: true });
            fetch('/api/messages', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(this.state.message)
            })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        this.setState({
                            error: false,
                            submitting: false,
                            message: {
                                to: '',
                                body: ''
                            }
                        });
                    } else {
                        this.setState({
                            error: true,
                            submitting: false
                        });
                    }
                });
        }
        // rest of the component
        onHandleChange(event) {
            const name = event.target.getAttribute('name');
            this.setState({
                message: { ...this.state.message, [name]: event.target.value }
            });
        }
        render() {
            return (
                <form
                    onSubmit={this.onSubmit}
                    className={this.state.error ? 'error sms-form' : 'sms-form'}  >
                    <div>
                        <input type="tel" name="to" id="to" value={datass.phone} onChange={e => this.onHandleChange(e, e.target.value)}/>
                    </div>
                    <Button className="buttonForLancerMaybe" type="submit" disabled=
                        {this.state.submitting}>SMS</Button>
                </form>
            );
        }
    }
export default SmsForm;

Upvotes: 1

Related Questions