AZSWQ
AZSWQ

Reputation: 319

React Redux - Take Data from payload and display in component

I am new to redux but got as far as the payload of my search results. Currently I am displaying the results without using redux for testing purposes only using createListItems () function.

Here is the code of the component.

UPDATED based on answer below

  handleSubmit(event) {
    event.preventDefault()
    const apiSearchURL = `api}`
    get(apiSearchURL, { maxContentLength: 400 })
    .then((searchResults) => {
      this.props.dispatch(getSearchResults(searchResults))
    })
  }


  renderData = (props) => (
    <div>
      <p> {props.user.username} </p>
    </div>
  )

  render() {

    return (
      <div className="my-4">
        <div className="recomm">
          <div className="recomm_top">
            <span>Search</span>
          </div>
        </div>
        <div className="search_advan_box">
          <form onSubmit={this.handleSubmit.bind(this)}>
            <select
              name="religion"
              className="mb-2"
              value={this.state.formValues['religion']}
              onChange={this.handleChange.bind(this)}
            >
            ...

            <input
              type="submit"
              className="my-4 pri_btn p-2"
              value="Search Profiles"
            />
          </form>
            <h1>NEW Results</h1>
            { this.props.data
              ? this.props.data.map(user =>
              <this.renderData key={user.id} user={user} />)
              : null
            }
        </div>
      </div>
    )
  }
}

const mapStateToProps = state => ({
  data: state.data,
})

export default connect(mapStateToProps)(SearchAdvanced)

Upvotes: 0

Views: 2290

Answers (1)

iqbal125
iqbal125

Reputation: 1431

You will need to connect your component to the redux state with mapStatetoProps.

function mapStateToProps(state) {
    return {
        data: state.data
    };
}

Since it is async, you will need to use a ternary expression as well as .map() to actually render the data to the screen.

         { this.props.data
           ? this.props.data.map(item =>
           <this.renderData key={item.id} item={item} />)
           : null
         }

Finally a functional component

renderData = (props) => (
    <div>
      <p> {props.item.username} </p>
      <p> {props.item.firstname} </p>
    </div>
  )

Upvotes: 1

Related Questions