Search code examples
reactjsrenderingstatereduxupdating

Redux State Not Updating/Rerendering


I have a component with an action creator that, on componentWillMount, retrieves data which is then stored in a redux property. My problem is that the data retrieved is not put in the filteredPhotos redux store.

The only way I can see the new data in redux is if I go to another page. That's when I can see the filteredPhotos store with data. How can I render the new data in the store immediately?

Reducer.js

import { 
    PHOTOS
} from '../actions/types';


const INITIAL_STATE = {  filteredPhotos:[] };

export default function(state = INITIAL_STATE, action) {
  switch (action.type) {
    case PHOTOS:
        console.log("THIS IS THE NEW DATA");
        console.log(action.payload.data);
      return {...state, filteredPhotos: action.payload.data};
  }
  return state;
}

Action index.js

import { combineReducers } from 'redux';
import { reducer as formReducer } from 'redux-form';

import ImageReducer from './Reducer.js';

const rootReducer = combineReducers({
  images: ImageReducer
});

export default rootReducer;

action.js

import axios from 'axios';
const API_URL = 'http://jsonplaceholder.typicode.com/photos'; 

import {
  PHOTOS,
} from './types';


export function fetchPhotos() {
  return function(dispatch) {
    axios.get(`${API_URL}`, {withCredentials: true})
    .then(response => {
      dispatch({
        type:PHOTOS,
        payload: response
      });
    })
   .catch(() => {
      console.log("Not working"");
    });
  }
}

Component.js

class Test extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      testing:false,
    };
  }

componentWillMount() {
    this.props.fetchPhotos();
}

.... 

Solution

  • In componentWillMount() you need to dispatch(this.props.fetchPhotots()). Otherwise the action creator won't have access to dispatch (assuming you are also using redux-thunk middleware)

    EDIT:

    If the component is connected then dispatch is available in this.props:

    const {dispatch, fetchPhotos} = this.props;
    dispatch(fetchPhotos());