0
votes

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.

1
I think the issue is in mapStateToProps. It should be state.REDUCER. forumPosts You can try to do a console.log(state) before your return to see your structure! - Tobias Lins
Hi there Tobi, Yes I did try to console.log(state) it gives me the two object the previous null empty state and the one after the posts finished downloaded - fredi tansari
Yes but does the object has a key? Like state: {postReducer: null} and {postReducer: {forumPosts: ....}} - Tobias Lins

1 Answers

0
votes

I think you are making mistake in reducer, as I can see that you're expecting a array of object as posts and you are using spread operator with object instead of array, try this it will solve your issue,

const initialState = [{}];

const forumPosts = (state = initialState , action) => {


    switch(action.type) {

        case "FETCH_POST":
            return  [ ...state, ...action.payload ]; // merging 2 arrays using spread oprator

        default:
            return state;

    }
}

export default forumPosts;