1

I have a simple functional component in React, that renders the search results. If there are results, it renders the names of users, if there are no results, it renders a message no public records found. The problem is that the message is rendered when the component is loaded, whereas I want to show it only when there are no results in serp array. I don't want to change it into class component just because of that, and I'm sure there's a way to "skip" the rendering of the message when the component loads.

Could you help figure it out?

import React from "react";
import { withRouter } from "react-router-dom";
import { connect } from "react-redux";
import PropTypes from "prop-types";

const SearchResults = ({ auth: { user }, search: { users, loading } }) => {
  let serp;

  if (users.length !== 0) {
    serp = users.map((item, i) => {
      return <div key={i}>{item.name}</div>;
    });
  } else {
    return <div>no public record found</div>;
  }

  return <div className="dashboard-container">{serp}</div>;
};

SearchResults.propTypes = {
  auth: PropTypes.object.isRequired,
  search: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  auth: state.auth,
  search: state.search
});

export default connect(mapStateToProps)(withRouter(SearchResults));

2 Answers 2

2

You can make use of loading like this:

const SearchResults = ({ auth: { user }, search: { users, loading } }) => {
  let serp;

  if (users.length !== 0) {
    serp = users.map((item, i) => {
      return <div key={i}>{item.name}</div>;
    });
  } else {
    if (loading) {
      return <div>Loading...</div>;
    } else {
      return <div>no public record found</div>;
    }
  }

  return <div className="dashboard-container">{serp}</div>;
};
Sign up to request clarification or add additional context in comments.

Comments

2

Since SuleymanSah has suggested that you should make use of the loading prop to create a loading effect, below is my suggestion for better readability:

  1. Create a HOC called withLoading like this:
const withLoading = isLoading => WrappedComponent =>
  isLoading ? <div>Loading...</div> : WrappedComponent;
  1. Make use of withLoading like this inside your component:
const SearchResults = ({ auth: { user }, search: { users, loading } }) => {
  ...
  return (
   <div className="dashboard-container">
     {withLoading(loading)(...)}
   </div>;
  )
};

Having too many if/else like that will slow you down while reading code in the future. Please also consider using Inline If-Else with Conditional Operator for better readability too.

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.