0
votes

I am new to redux and it might be some silly error. I am trying to make an Api call in Action and pass the data to the Reducer. I can see the data passed correctly in the reducer with action.data. I think the problem is in mapStateToProps in the component therefore I am not able to pass the state and render the component. Please find below action - reducers - store.js - home.js

ACTION.JS

export const DATA_AVAILABLE = 'DATA_AVAILABLE';


export function getData(){
    return (dispatch) => {

        //Make API Call
   
        fetch("MY API URL").then((response) => {
          return response.json();
        }).then((data) => {
                    var data  = data.articles;
                    console.log(data)
                    dispatch({type: DATA_AVAILABLE, data:data});
        })
    };
}

this is Reducers.JS

import { combineReducers } from 'redux';

import { DATA_AVAILABLE } from "../actions/" //Import the actions types constant we defined in our actions

let dataState = {
  data: [],
  loading:true
};

const dataReducer = (state = dataState, action) => {
    switch (action.type) {
        case DATA_AVAILABLE:
        state = Object.assign({}, state, {
              data: [
                ...action.data //update current state data reference
              ],
              loading: false

            });
console.log(action.data);
            return state;
        default:
            return state;
    }
};

// Combine all the reducers
const rootReducer = combineReducers({
    dataReducer
    // ,[ANOTHER REDUCER], [ANOTHER REDUCER] ....
})

export default rootReducer;

this is Store.js with Redux-thunk

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

import reducers from '../app/reducers/index'; //Import the reducer

// Connect our store to the reducers
export default createStore(reducers, applyMiddleware(thunk));

and finally home.js component when I need to pass the new state and render it

'use strict';

import React, { Component } from 'react';
import {
    StyleSheet,
    FlatList,
    View,
    Text,
    ActivityIndicator
} from 'react-native';

import {bindActionCreators} from 'redux';
import { connect } from 'react-redux';

import * as Actions from '../actions'; //Import your actions

class Home extends Component {
    constructor(props) {
        super(props);
        this.state = {
        };
    }

    componentDidMount() {
        this.props.getData(); //call our action
    }

    render() {
        if (this.props.loading) {
            return (
                <View style={styles.activityIndicatorContainer}>
                    <ActivityIndicator animating={true}/>
                </View>
            );
        } else {
          console.log(this.state)
            return (
              <View style={styles.row}>
                  <Text style={styles.title}>
                  {this.props.data}
                  fomrmo
                  </Text>
                  <Text style={styles.description}>
                  </Text>
              </View>
            );
        }
    }


};



// The function takes data from the app current state,
// and insert/links it into the props of our component.
// This function makes Redux know that this component needs to be passed a piece of the state
function mapStateToProps(state, props) {

    return {
        loading: state.dataReducer.loading,
        data: state.dataReducer.data
    }

}

// Doing this merges our actions into the component’s props,
// while wrapping them in dispatch() so that they immediately dispatch an Action.
// Just by doing this, we will have access to the actions defined in out actions file (action/home.js)
function mapDispatchToProps(dispatch) {
    return bindActionCreators(Actions, dispatch);
}

//Connect everything
export default connect(mapStateToProps, mapDispatchToProps)(Home);
1
does your View get rendered? if so what is the value of {this.props.data} ? - Tomasz Mularczyk
@Tomasz the view is rendered and {this.props.data} does not render anything. If I console.log(this.props.data) it says Array: [] - (empty unfortunately) - Alessio Chiffi
can you verify that var data = data.articles; is not an empty array in a response? - Tomasz Mularczyk
@Tomasz I have just double checked and it's returning the array with the object correctly. Also in reducer.js when I console.log(action.data) I can see the data populated with the object correctly. It's a mystery why this is not passed to the component :) - Alessio Chiffi
is it an plain Object or Array? - Tomasz Mularczyk

1 Answers

0
votes

Assuming that:

    case DATA_AVAILABLE:
      console.log(action.data.length) 

will console.log something more than 0

change your reducer action:

const dataReducer = (state = dataState, action) => {
    switch (action.type) {
        case DATA_AVAILABLE:
          return {
            ...state,
            data: action.data,
            loading: false    
          });
        default:
            return state;
    }
};

To address:

Objects are not valid as a React child(found objects with Keys {source, author, title, description, url })

that's because you try to render Object:

{this.props.data}

but if you do:

{
   this.props.data.map((el, i) => 
     <p key={i}>Element nr {i}</p> 
   )
}

It should work.