I tried to do some react fetching api from typicode.com, but somehow it returns 2 set of props. One null and the other is the actual data.
I have tried removing the initial state in the reducer. I have moved the calls from componentDidMount lifecycle hook to componentWillMount().
I have been using redux thunk middle ware.
These are the reducers:
const initialState =[{}]
const postReducer = (state=initialState , action) =>{
switch(action.type){
case "FETCH_POST":
return { ...state, forumPosts:action.payload};
default:
return state;
}
}
export default postReducer;
these are the actions:
import axios from 'axios';
export const fetchPosts = ()=>dispatch =>{
axios.get(`https://jsonplaceholder.typicode.com/posts`)
.then(res =>(
dispatch({type: "FETCH_POST", payload:res.data })
)
)
.catch(err => dispatch({type: "FETCH_POST", payload : {}}))
}
these are the main apps:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { connect } from 'react-redux';
import {fetchPosts} from './actions/postActions'
class App extends Component {
componentWillMount(){
this.props.fetchPosts();
}
render() {
const {forumPosts } = this.props;
console.log(forumPosts)
return (
<div className="App">
</div>
)
}
}
const mapStateToProps = (state) =>{
return{
forumPosts : state.forumPosts
}
};
export default connect(mapStateToProps, {fetchPosts})(App);
here are the store:
const store = createStore(postReducer, applyMiddleware(thunk));
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
The expected result is list of dummy posts from typicode, but it returns null first then the actual dummy data.
mapStateToProps. It should bestate.REDUCER. forumPostsYou can try to do a console.log(state) before your return to see your structure! - Tobias Lins{postReducer: null}and{postReducer: {forumPosts: ....}}- Tobias Lins