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:

exportconstSEARCH = 'SEARCH';

exportfunctionsearch(value) {
  return {type: SEARCH, value};
}

Then your reducer might look like this:

import {SEARCH} from'./actions';

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

exportdefaultfunctionreducer(state = initialState, action) {
  switch(action.type) {
    caseSEARCH: {
      const {value} = action;
      const works = state.contents.filter((val) => val.includes(value));
      return {...state, value, works};
    }
    default:
      return state;
  }
}

Then in your SearchBar:

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

classSearchBarextendsComponent {
  render() {
    const {search, value} = this.props;

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

functionmapStateToProps({works}) {
  return {value: works.value};
}

functionmapDispatchToProps(dispatch) {
  returnbindActionCreators({search}, dispatch);
}

exportdefaultconnect(mapStateToProps, mapDispatchToProps)(SearchBar);

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

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

classWorkListextendsComponent {
  render() {
    const {works} = this.props;

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

functionmapStateToProps({works}) {
  return {
    works: works.works
  }
}

exportdefaultconnect(mapStateToProps)(WorkList);

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