Help storing API data in Redux rather than in component state

Help storing API data in Redux rather than in component state
0

#1

I’m working on learning Redux and I am attempting to store data from the NASA picture of the day API in Redux store rather than storing it in the React component’s local state. I’ve followed a few tutorials but can’t seem to get this working.

Here is the tutorial I am following along with’s Github repo

A lot of it seems straight forward but I am getting an error when trying to use this.props.dispatch(). I get a “not a function” error.

Here is my project. The relevant Redux files are in the client/src/actions and client/src/reducers folders plus the index.js, store.js, and PictureOfTheDay component.

Here is the chunk of code with the error in PictureOfTheDay.js

import React, { Component } from 'react';
import {connect} from 'react-redux';

import {fetchPOD} from './actions/pod-action';

connect((store) => {
  return {
    pod: store.podData
  };
})

export default class PictureOfTheDay extends Component {
  componentWillMount() {
    this.props.dispatch(fetchPOD());
  }

  render() {
    const {pod} = this.props;

    return (
      <div>
        {pod}
      </div>
    )
  }
}

Where am I going wrong here? I have a feeling it’s an issue using connect().


#2

connect is a function that injects redux-related props into your component. You need to export it.
Maybe this could work :

import React, { Component } from 'react';
import {connect} from 'react-redux';

import {fetchPOD} from './actions/pod-action';


// Keep the export for testing purpose
export  class PictureOfTheDay extends Component {
  componentDidMount() {
    this.props.fetchPOD();
  }

  render() {
    const {pod} = this.props;

    return (
      <div>
        {pod}
      </div>
    )
  }
}



// This is storing the response inside redux store?
const mapDispatchToProps = dispatch => ({
fetchPOD: () => dispatch(fetchPOD())
})

// Get the result which has been stored
const mapStateToProps = state => ({
pod: state.pod .  
})

// This is the component that you are going to use in some other component
export default connect(mapStateToProps, mapDispatchToProps)(PictureOfTheDay);

And I took a look to your project afterwards. It seems like you’re importing reducer.js in your store.js file. There is no such file. Plus, I am not sure of that but I think that if you need multiple reducers you wiil have to use something like combineReducer in your store creation.
Good luck with your project !