Home > Enterprise >  How to display data to input field after fetching data in reactjs
How to display data to input field after fetching data in reactjs

Time:09-22

I am fetching data from an API and would like to know how to set that fetched date in input fields. its seems like an absolute beginner problem, anyhow kindly help me of this.

Here is my code:

export default function Consumerdetails() {

  const [consumer, getConsumer] = useState([]);
  useEffect(() => {
    httpClient(url   `/api/consumers`).then((res) => {
      console.log('Success:', res)
    })
    .catch(err => {
      console.log('An error occurred:', err.res)
    });
  });

return (
<div>
<TextField
   required
   id="outlined-required"
   label="User Name"
   variant="outlined"
   name="username"
   value={consumer.username} onChange={getConsumer}
/>

<TextField
   required
   id="outlined-required"
   label="Phone Number"
   variant="outlined"
   name="phone"
   value={consumer.phone} onChange={getConsumer}
/>
</div>
})

CodePudding user response:

useEffect(() => {
  httpClient(url   `/api/consumers`).then((res) => {
    getConsumer(res.data) // you store the data
  })
  .catch(err => {
    console.log(err)
  });
},[]);

Check if it is works for you

CodePudding user response:

you can set API response data like this

export default function Consumerdetails() {
  const [consumer, setConsumer] = useState([]);

  // dummy json data
  const data = {
    username: "xyz",
    mobile: "123456789",
  };

  useEffect(() => {
    // your api data
    setConsumer(data);
  }, []);

  const onChange = (event) => {
    // here set change value
    setConsumer(event.target.value);
  };

  return (
    <div>
      <TextField
        required
        id="outlined-required"
        label="User Name"
        variant="outlined"
        name="username"
        value={consumer.username}
        onChange={onChange}
      />

      <TextField
        required
        id="outlined-required"
        label="Phone Number"
        variant="outlined"
        name="phone"
        value={consumer.mobile}
        onChange={onChange}
      />
    </div>
  );
}

CodePudding user response:

You can assign api response to state and assign state to input fields.

export default function Consumerdetails() {

  const [consumer, getConsumer] = useState({});
  
  useEffect(() => {
    httpClient(url   `/api/consumers`)
    .then(res => res.json()
    .then((data) => {
        setConsumer(data);
    })
    )
    .catch(err => {
      console.log('An error occurred:', err.res)
    });
  },[]);

return (
<div>
<TextField
   required
   id="outlined-required"
   label="User Name"
   variant="outlined"
   name="username"
   value={consumer?.username} onChange={getConsumer}
/>

<TextField
   required
   id="outlined-required"
   label="Phone Number"
   variant="outlined"
   name="phone"
   value={consumer?.phone} onChange={getConsumer}
/>
</div>
})

  • Related