0

I am able to save data into my database. However, i want to know how to show/render the fetch data on my screen after i run my fetch request.

When i add data i am able to push to render on my page. But what i want is, once i run my fetch data function, how do i render the response that i get onto my screen ?

My Json data after fetch looks like this when i console.log(json.data.shipping)

0: { name: "Samsung A10", phone: "001-2342-23429"}
1: {name: "Iphone Xs", phone: "001-12193-1219"}

PS: Beginner with React JS

Below is how i save data

state = {
      shippings: userData,
      addNewData: {
         name: '',
         phone: ''
      },
   };



addData() {
      const { name,phone} = this.state.addNewData;
      if (name!== '' && phone = "") {
         let newData = {
            ...this.state.addNewData,
            id: new Date().getTime()
         }
         let shippings = this.state.shippings;

      fetch( 'http://facicla:5000/api', {
      method:'post',
      /* headers are important*/
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'       
        body: JSON.stringify(this.state.addNewData)
  })
  .then(response => {
     return response.json();
     shippings.push(newData);
     NotificationManager.success('Sucess!');
  })    
      }
   }

userData

 export default [
        {
            name: 'Shipping-Car',
            phone: '001-72342-2342',
        } ]

Fetch Data

fetchAllData(){
      return this.fetchPost().then(([response,json]) => {
         if(response.status === 200)
         {
            console.log(json.data.shipping)
         0: { name: "Samsung A10", phone: "001-2342-23429"}
         1: {name: "Iphone Xs", phone: "001-12193-1219"}
         }
      })
   }

   fetchPost(){
      const URL = 'http://facicla:5000/api';
      return fetch(URL, {method:'GET',headers:new Headers ({
         'Accept': 'application/json',
         'Content-Type': 'application/json', 
      })})
      .then(response => Promise.all([response, response.json()]));
   }

Render

render() {
      const { shippings, addNewData} = this.state;
      return (
         <div className="wrapper">
            <div className="row row-eq-height">
               {shippings.map((shipping, key) => (
                  <div className="col-sm-3 col-md-3 col-lg-3" key={key}>
                        <div className="d-flex justify-content-between">
                        <h5 className="fw-bold">{shipping.name}</h5></a>
                        <h5 className="fw-bold">{shipping.phone}</h5></a>

                        </div>                          
                  </div>  
               ))}
            </div>
}
5
  • You must only change state using this.setState(), that includes appending to arrays. Replace shippings.push(newData); with this.setState({ shippings: [...shippings, newData] }); Commented Jun 28, 2019 at 6:48
  • So, you want to store json.data.shipping in the shipping right? Commented Jun 28, 2019 at 6:55
  • @AddWebSolutionPvtLtd yes, i want it to show when the page loads...When user loads page, i run the fetch data function so the page must be populated with ` json.data.shipping` Commented Jun 28, 2019 at 6:56
  • @RoboPHP Try and run the function which fetches data in the component lifecycle method componentDidMount(). And there you can populate the state object Commented Jun 28, 2019 at 6:58
  • @minus.273, yes i already have componentDidMount() which runs the function. My issue is how to populate the state object to be rendered on my page Commented Jun 28, 2019 at 6:59

1 Answer 1

1

Try this:

fetchAllData(){
      return this.fetchPost().then(([response,json]) => {
         if(response.status === 200)
         {
            console.log(json.data.shipping)
            this.setState(
          { shippings: Object.values(json.data.shipping)
             //or shippings: json.data.shipping 
          } 

          )


         //0: { name: "Samsung A10", phone: "001-2342-23429"}
         //1: {name: "Iphone Xs", phone: "001-12193-1219"}
         }
      })
   }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.