Skip to content Skip to sidebar Skip to footer

React-Redux - Create A Search Filter

i need help to make a Search Filter in my app. Its a simple app, used for study purposes. The objective is to create a search filter. i have the state in search_bar container and i

Solution 1:

It looks like your code is missing some key elements for Redux to work. You need to dispatch a Redux action when your search input changes that will in turn update the store. Right now you're merely setting the local state of SearchBar when the input changes. Secondly, your reducer doesn't modify the state, it's always returning the same array.

Something along these lines.

Your actions file might look like this:

export const SEARCH = 'SEARCH';

export function search(value) {
  return {type: SEARCH, value};
}

Then your reducer might look like this:

import {SEARCH} from './actions';

const initialState = {contents: ['Mirististica', 'Vet'], value: '', works: []};

export default function reducer(state = initialState, action) {
  switch(action.type) {
    case SEARCH: {
      const {value} = action;
      const works = state.contents.filter((val) => val.includes(value));
      return {...state, value, works};
    }
    default:
      return state;
  }
}

Then in your SearchBar:

import React, {Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {search} from './actions';

class SearchBar extends Component {
  render() {
    const {search, value} = this.props;

    return (
        <input
          className="form-control"
          placeholder = "Procurar Trabalho"
          onChange={(e) => search(e.target.value)}
          value={value} />
    );
  }
} 

function mapStateToProps({works}) {
  return {value: works.value};
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({search}, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(SearchBar);

Your WorkList component merely needs to listen for changes to works in the Redux store.

import React, { Component } from 'react';
import { connect } from 'react-redux';

class WorkList extends Component {
  render() {
    const {works} = this.props;

    return (
      <table className="table table-hover">
        <thead>
          <tr>
            <th>Nome</th>
          </tr>
        </thead>
        <tbody>{works.map((work) => <tr key={work}><td>{work}</td></tr>)}</tbody>
      </table>
    );
  }
}

function mapStateToProps({works}) {
  return {
    works: works.works
  }
}

export default connect(mapStateToProps)(WorkList);

Post a Comment for "React-Redux - Create A Search Filter"