Search code examples
reactjsfunctioncomponentsrenderreact-component

React - why is my div not displayed on the page from my for loop function


I am writing a UI page to display a list of new messages, but I have gone wrong gin my code somewhere and not all of my page renders. I can't seem to find where.

My arrays correctly capture the data as I have tested this in console.log.

The text that should render on the page from the "displayNewMessage" doesn't work. Everything else renders.

Can anyone see where I have gone wrong please?

class Welcome extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      messageData: [],
      newMessages: [],
      isLoading: false
    };
  }

  componentDidMount() {
    this.setState({ isLoading: true });
    this.setState({ userID: this.props.location.state });
    const serachByUserId = this.props.location.state;
    const proxyurl = "https://cors-anywhere.herokuapp.com/";
    const url =
      "my-url" +
      serachByColleagueId;
    fetch(proxyurl + url)
      .then((res) => res.json())
      .then((data) => this.setState({ data: data }))
      .then(
        fetch(
          proxyurl +
            "my-URL"
        )
          .then((res) => res.json())
          .then((messageData) =>
            this.setState(
              { messageData: messageData, isLoading: false },
              () => {}
            )
          )
      );
  }

  render() {
    const { data, isLoading, messageData } = this.state;
    if (isLoading) {
      return (
        <div className="pageLoading">
          <p>Loading...</p>
        </div>
      );
    }

    return (
      <div>
        <div>
          <p>
            <strong>
              Welcome {data.Forename} {data.Surname}
            </strong>
          </p>
         </div>
        <div className="InfoBox">
          <p>
            <strong>Message Backlog</strong>
          </p>
          <p className="helpText">
            The below Orders have open chats awaiting a response. Click on
            the order number to send and view messages.
          </p>
        </div>
        {this.getMessages(messageData)}
      </div>
    );
  }

  getMessages(messageData) {
    var newMessagesArray = [];
    var latestMessageIndex;
    var latestMessage;

    messageData.message_Subjects.forEach(saveNewMessage);

    function saveNewMessage(sub) {
      console.log(sub);
      latestMessageIndex = sub.message_Chain.length - 1;
      latestMessage = sub.message_Chain[latestMessageIndex];
      if (latestMessage.sentFromId.toString().length === 7) {
        var message_Chain = {
          dateTime: latestMessage.dateTime,
          sentFromId: latestMessage.sentFromId,
          messagebody: latestMessage.messageBody,
          messageChainId: latestMessage.messageChainId,
        };
        var message_subject = {
          userId: sub.userId,
          subjectId: sub.messageSubjectId,
          subject: sub.subject,
          message_Chain: message_Chain,
        };
        newMessagesArray.push({ message_Subject: message_subject });
      } else {
        // do nothing
      }
    }

    if (newMessagesArray.length > 0) {
      return ( <div>{newMessagesArray.forEach(displayNewMessage)}</div>)
    } else {
      return <p>No New messages.</p>;
    }

    function displayNewMessage(arrayItem) {
      console.log(arrayItem);
      return (
        <div>
          <ul>
            <li>Subject = {arrayItem.message_Subject.subject}</li>
            <li>Order number = {arrayItem.message_Subject.orderNumber}</li>
            <li>Date and Time = {arrayItem.message_Subject.dateTime}</li>
            <li>
              message = {arrayItem.message_Subject.message_Chain.messageBody}
            </li>
            <li>
              sent by = {arrayItem.message_Subject.message_Chain.sentFromId}
            </li>
          </ul>
        </div>
      );
    }
  }
}

export default Welcome;

Solution

  • Found away around this not rendering on the page with no need for the displayNewMessage function.

    if (newMessagesArray.length > 0) {
          return (
          newMessagesArray = newMessagesArray.map((item) =>
            <li key={item.id}>Subject = {item.message_Subject.subject}</li>
            <li> etc..... </li>
            ))
        } else {
          return <p>No New messages.</p>;
        };