0

i am trying to fetch a series api-data. as per below api-data each series have their own data, for e.g a series "bannerData" have their data id,banner_title... and next series "homecatData" have their data like id,category_title... and so on up to last series.
in my case, endpoint api is "http://localhost:8000/api/homepage/"

how to fetch this data in reactjs?

i am probably new to reactjs. it would be great if anybody could help me out what i am trying to solve is. thank you so much in advance.

{
    "bannerData": [
        {
            "id": 2,
            "banner_title": "CORONA sell",
            "banner_image": "http://localhost:8000/media/hero_man.png",
            "discount_price": 86,
            "product_category": "7"
        }
    ],
    "homecatData": [
        {
            "id": 7,
            "category_title": "new-arrival",
            "category_slug": "new-arrival",
            "category_description": "",
            "category_image": "http://localhost:8000/media/cat2.jpg"
        },
    ],
    "homeproductData": [
        {
            "_id": 9,
            "product_title": "product05",
            "product_price": 21,
            "product_image": "http://localhost:8000/media/product4_JOvGftO.png",
            "product_new": false
        },
        {
            "_id": 7,
            "product_title": "product03",
            "product_price": 21,
            "product_image": "http://localhost:8000/media/product3.png",
            "product_new": false
        },

    ],
}

2
  • You need to show what you've tried. There are many ways to do it. Show us how you are trying to do it. Commented Apr 18, 2020 at 3:15
  • take a look this link pastebin.com/WM9tPwsL @TJBlackman Commented Apr 18, 2020 at 3:22

4 Answers 4

1

There are many ways fetch data in react. One of the most common way is to fetch using a package called axios. Since you are using a class-based component, It will look like this.

Here's a working sandbox as per your request.

import React, { Component } from "react";
import axios from 'axios'
import Data from "./contact.js";

    export default class App extends Component {
      state = {
        results: [],
        isLoading: false,
      };

      componentDidMount() {
        this.fetchData();
      }

      fetchData = async () => {
        this.setState({ isLoading: true });
        try {
          const response = await axios.get("http://localhost:8000/api/homepage/");
          this.setState({ results: response, isLoading: false });
        } catch (error) {
          console.log(error);
        }
      };

      render() {
        if (this.state.isLoading) {
          return "Loading...";
        }
        return <Data results={this.state.results} />;
      }
    }

You are trying to map an object in your contact.js file. You can always destructure them or you have to explicitly access the array you want using the dot operator and also in react you have to use className instead of just class when using it.

import React from "react";

const Data = ({ results }) => {
  if (!results) {
    return "";
  }
  const { bannerData, homecatData } = results;
  return (
    <div>
      <center>
        <h1>Banner Data</h1>
      </center>
      {bannerData.map((bannerData) => (
        <div className="card">
          <div className="card-body">
            <h5 className="card-title">{bannerData.banner_title}</h5>
            <h6 className="card-subtitle mb-2 text-muted">
              {bannerData.banner_image}
            </h6>
            <p className="card-text"></p>
          </div>
        </div>
      ))}

      <center>
        <h1>Home Category Data</h1>
      </center>
      {homecatData.map((homecatData) => (
        <div className="card">
          <div className="card-body">
            <h5 className="card-title">{homecatData.category_title}</h5>
            <h6 className="card-subtitle mb-2 text-muted">
              {homecatData.category_image}
            </h6>
            <p className="card-text"></p>
          </div>
        </div>
      ))}
    </div>
  );
};

export default Data;
Sign up to request clarification or add additional context in comments.

20 Comments

thanks for your quick response. next how to map the fetch data in my "./src/contact.js" and how to pass the value as a parameter?
I see that you have already mapped those data in your contact.js file. Is it now working?
response.json() axios does not have .json method
You did not mention the error. What do you imply by clean code? I just forgot to await a promise. I have only added a fetchData() function apart from your original code.
Yeah sure. Thanks @xdeepakv
|
1

You could fetch from each main json data (bannerData,homecatData,homeproductData)

export const fetchbannerData = ()  =>{
        return fetch(baseurls+'bannerData')
            .then(response => {
                    if (response.ok) {
                        return response;
                    } else {
                        var error = new Error('Error ' + response.status + ': ' + response.statusText);
                        error.response = response;
                        throw error;
                    }
                },
                error => {
                    var errmess = new Error(error.message);
                    throw errmess;
                })
            .then(response => response.json())
    }

Comments

0

Axios would help you to fetch api data.
type npm I axios on terminal to use axis to fetch data

visit https://www.npmjs.com/package/axios to install axis and learn how to use it

Comments

0

Using fetch native javascript. You can customize using useEffect, useState, or async-await.

//const React = require("react")
//const ReactDOM = require("react-dom")

const baseURL = "https://api.whatdoestrumpthink.com/api/v1/quotes/";
class App extends React.Component {
  state = {
    quotes: [],
    loading: false,
  };

  componentDidMount() {
    this.getQuotes();
  }
  getQuotes() {
    this.setState({ loading: true });
    try {
      fetch(baseURL)
        .then(response => response.json())
        .then((response) => {
          this.setState({
            quotes: response.messages.personalized,
            loading: false,
          });
        });
    } catch (error) {
      console.log(error);
      this.setState({ loading: false });
    }
  }

  render() {
    const { quotes, loading } = this.state;
    if (loading) {
      return "Loading Quotes...";
    }
    return <Quotes quotes={quotes} />;
  }
}
function Quotes({ quotes = [] }) {
  return quotes.map((quote, index) => (<div key={index}>{quote}</div>));
}
ReactDOM.render(<App />, document.getElementById("root-app"));
<div id="root-app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

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.