I'm struggling to learn React-Redux. I'm making a simple application that fetch data from Teleport API and show the list according to the user's input.
My issue is that even though action is dispatched in container component, state is not changed and the result does not show up.
This is a screenshot of console after dispatching action twice.
I suppose that there is an issue to store data properly. I appreciate if you can help me.
Here is my code.
/container/search.js
class Search extends Component{
constructor(props){
super(props);
this.state = {
city : ""
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
console.log(event.target.value)
this.setState({
city: event.target.value
});
}
handleSubmit(event){
event.preventDefault();
console.log(this.state.city)
this.props.addData(this.state.city);
this.setState({
city: ""
});
}
render(){
return(
<div>
<form onSubmit={this.handleSubmit}>
<input type="text"
placeholder="add city name"
onChange={this.handleChange}
value={this.state.city} />
<button>Submit</button>
</form>
</div>
)
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ addData }, dispatch);
}
export default connect(null, mapDispatchToProps)(Search);
/actions/index.js
import axios from 'axios';
const ROOT_URL = "https://api.teleport.org/api/cities/?search";
const ADD_DATA = 'ADD_DATA';
export function addData(city){
const url = `${ROOT_URL}=${city}`;
const request = axios.get(url);
return {
type: ADD_DATA,
payload: request
};
}
/reducers/reducer_data.js
import { ADD_DATA } from "../actions/index";
export default function( state=[], action) {
switch(action.type) {
case ADD_DATA:
return [action.payload.data, ...state];
}
return state;
}
/reducers/index.js
import { ADD_DATA } from "../actions/index";
export default function( state=[], action) {
switch(action.type) {
case ADD_DATA:
return [action.payload.data, ...state];
}
return state;
}
//EDIT // index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import promiseMiddleware from 'redux-promise';
import logger from 'redux-logger'
import reducers from './reducers';
import Search from './containers/search';
const createStoreWithMiddleware = applyMiddleware(promiseMiddleware, logger)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<Search />
</Provider>
, document.querySelector('.container'));