RossWalker
RossWalker

Reputation: 3

Data from database displaying in the State but not on screen in React.js

I am new to react and designing an eCommerce website. In the admin side of the website, I have created a database to store customers information. I am able to write to the database and read from it (data is appearing in the state) but I am not able to display the data on screen. I have a function called 'displayCustomerList' to get the data from the state and format it but in the Render part, nothing is being displayed. Any help or advice is much appreciated.

import React, { Component } from "react";
import Title from "./Title";
import { Link, Redirect } from "react-router-dom";
import { ButtonContainer } from "./Button";
import axios from "axios";

export default class Admin extends Component {

constructor(props) {
    super(props);
    const token = localStorage.getItem("token");

    let loggedIn = true;
    if (token == null) {
      loggedIn = false;
    }

    this.state = {
      loggedIn,
      name: "",
      address: "",
      postcode: "",
      phone: "",
      posts: [],
    };
  }

  componentDidMount = () => {
    this.getCustomerList();
  };

  getCustomerList = () => {
    axios
      .get("/api")
      .then((response) => {
        const data = response.data;
        this.setState({ posts: data });
        console.log("Data has been received");
      })
      .catch(() => {
        alert("Error retrieving data");
      });
  };

  handleChange = ({ target }) => {
    const { name, value } = target;
    this.setState({ [name]: value });
  };

  submit = (event) => {
    event.preventDefault();

    const payload = {
      name: this.state.name,
      address: this.state.address,
      postcode: this.state.postcode,
      phone: this.state.phone,
    };

    axios({
      url: "/api/save",
      method: "POST",
      data: payload,
    })
      .then(() => {
        console.log("Data has been sent to the server");
        this.resetUserInputs();
        this.getCustomerList();
      })
      .catch(() => {
        console.log("Internal server error");
      });
  };

  resetUserInputs = () => {
    this.setState({
      name: "",
      address: "",
      postcode: "",
      phone: "",
    });
  };

//THIS IS CAUSING THE ISSUE
  displayCustomerList = (posts) => {
    if (!posts.length) return null;

    console.log(posts) // I can see the array in the console

    posts.map((post, index) => (
      <div key={index} className="customer.list_display">
        <h3>TEST</h3> //NOT DISPLAYING
        <h3>{post.name}</h3>
        <p>{post._id}</p>
        <p>{post.address}</p>
        <p>{post.postcode}</p>
        <p>{post.phoneNumber}</p>
      </div>
    ));
  };

  render() {
    console.log("State: ", this.state);

    if (this.state.loggedIn === false) {
      return <Redirect to="/login" />;
    }

    return (
      <React.Fragment>
        <div className="py-5">
          <div className="container">
            <Title name="Admin" />
            <Link to="/">Logout</Link>
          </div>
        </div>
        <div className="card-footer d-flex justify-content-between">
          <form onSubmit={this.submit} className="py-5">
            <div className="form-input">
              <input
                type="text"
                name="name"
                placeholder="Name"
                value={this.state.name}
                onChange={this.handleChange}
                className="nameInput"
              />
            </div>
            <div className="form-input">
              <input
                type="address"
                name="address"
                placeholder="Address"
                value={this.state.address}
                onChange={this.handleChange}
                className="addressInput"
              />
            </div>
            <div className="form-input">
              <input
                type="text"
                name="postcode"
                placeholder="Postcode"
                value={this.state.postcode}
                onChange={this.handleChange}
                className="postcodeInput"
              />
            </div>
            <div className="form-input">
              <input
                type="text"
                name="phone"
                placeholder="Phone number"
                value={this.state.phone}
                onChange={this.handleChange}
                className="phoneInput"
              />
            </div>
            <ButtonContainer>submit</ButtonContainer>
          </form>
        </div>

        <div>
          {/* <CustomerList /> */}
          <Title name="Customer List" />
        </div>

        //NOTHING IS BEING DISPLAYED
        <div className="blog-">
          {this.displayCustomerList(this.state.posts)}
        </div>

      </React.Fragment>
    );
  }
}

Upvotes: 0

Views: 594

Answers (1)

vlad-grigoryan
vlad-grigoryan

Reputation: 322

you should return JSX object from displayCustomerList like this:

displayCustomerList = (posts) => {
if (!posts.length) return null;

console.log(posts) // I can see the array in the console

return posts.map((post, index) => (
  <div key={index} className="customer.list_display">
    <h3>TEST</h3> //NOT DISPLAYING
    <h3>{post.name}</h3>
    <p>{post._id}</p>
    <p>{post.address}</p>
    <p>{post.postcode}</p>
    <p>{post.phoneNumber}</p>
  </div>
));

};

Upvotes: 2

Related Questions