Why data is not loading from this dispatch action?

Viewed 112

I am trying to learn redux.

I watch some tutorials and follow along with them. These tutorials are with class component.

So I try to change these into functional component. Since I am just learning and not trying to make a big project I put actions, reducers and types into 1 file.

This is that file

import axios from 'axios';

export const FETCH_NEWS = 'FETCH_NEWS';

// Reducer
const initialState = {
  newsList: [],
};

export const articlesReducer = (state = initialState, action) => {
  switch (action.type) {
    case FETCH_NEWS:
      return {...state, newsList: action.payload};
    default:
      return state;
  }
};

export const fetchNews = () => (dispatch) => {
  axios
    .get('https://jsonplaceholder.typicode.com/users')
    .then((res) => {
      dispatch({
        type: FETCH_NEWS,
        payload: res.data,
      });
    })
    .catch((err) => {
      console.log(err);
    });
};

So I am using fetchNews props in News component

News component is like this

import { fetchNews }from '../../ducks/modules/Articles'
useEffect(() => {
        fetchNews();

        console.log('##############################')
        console.log(newsList)
        console.log('##############################')
},[])
const News = ({navigation, newsList, fetchNews}) => {

return (<View> ....  </View>)
}

News.propTypes = {
    fetchNews: PropTypes.func.isRequired,
    newsList: PropTypes.array.isRequired
}

const mapStateToProps = state => {
    return {
        newsList: state.articlesReducer.newsList
    }
}

export default connect(mapStateToProps, { fetchNews })(News);

As you can see I am console.logging in the useEffect hooks , I am console logging because no data are being loaded in the device

Here is a picture of empty array when component is mounted Console.log data

My store component is like this

const reducer = combineReducers({
  articlesReducer
});


const store = createStore(reducer, applyMiddleware(thunk,logger));
1 Answers

You are not dispatching the action correctly. I have added simpler way to use redux with function based components. You don't need to use connect.

export const fetchNews = () => (dispatch) => {
  axios
    .get('https://jsonplaceholder.typicode.com/users')
    .then((res) => {
      dispatch({
        type: FETCH_NEWS,
        payload: res.data,
      });
    })
    .catch((err) => {
      console.log(err);
    });
};

export const selectNewsList = (state) => state.newsList; // this is known as a selector.

And your view will be:

import { useSelector, useDispatch } from 'react-redux';
import { fetchNews, selectNewsList }from '../../ducks/modules/Articles'

const News = () => {

const newsList = useSelector(selectNewsList);
const dispatch = useDispatch();
useEffect(() => {
        dispatch(fetchNews());
},[])
console.log(newsList); // This will print empty array first, but will print again as data is populated.
return (<View> ....  </View>)
}
Related