简体   繁体   中英

redux reducer not listening for action

I have multiple actions in my app, and this one is just not listening or getting called to the next step, going to the reducer.

action file

    export const UPDATE_IMAGE_STATE = "UPDATE_IMAGE_STATE";
    export const updateImageState = imageData => {
      console.log(imageData)
      return {
        type: UPDATE_IMAGE_STATE,
        imageData
      }
    }

Note, the imageData payload is simply an object with two strings. Also, it definitely makes it to the action because it console.logs out fine.

reducer file

    import {
      UPDATE_IMAGE_STATE
    } from '../actions/image-action';

    const profileReducer = (state=initState, action) => {

        if (action.type === UPDATE_IMAGE_STATE) {
          console.log(action)
          return Object.assign({}, state, { 
            image: { 
              image: action.imageData.image,
              imageUrl: action.imageData.imageUrl
            } 
          })
        }

      return state;
    }

export default profileReducer;

Note, the console.log in the reducer even doesn't fire off. So it's not making it there for some reason, but you can see I've imported the action.

Also, I have other actions from the same file, going to the same reducer file that work. So everything seems to be connected.

store.js file

    import {createStore, combineReducers, applyMiddleware} from 'redux';
    import {reducer as formReducer} from 'redux-form';
    import thunk from 'redux-thunk';
    import profileReducer from './reducers/profile-reducer';

    const rootReducer = combineReducers({
      user: profileReducer,
      form: formReducer
    })

    export const store = createStore(rootReducer,applyMiddleware(thunk));

index.js file

    import React from 'react';
    import ReactDOM from 'react-dom';
    import './index.css';
    import App from './components/App';
    import reportWebVitals from './reportWebVitals';
    import {store} from './store';
    import { Provider } from 'react-redux';


    ReactDOM.render(
      <Provider store={store} >
        <React.StrictMode>
          <App />
        </React.StrictMode>,
      </Provider>,
      document.getElementById('root')
    );

    reportWebVitals();

here's the file upload-image.jsx this is where the action gets dispatched from

    import React, { Component } from 'react';
    import Axios from 'axios';
    import { connect } from 'react-redux';
    import { bindActionCreators } from 'redux';
    import { updateImageState } from '../actions/image-action';
    import { API_BASE_URL } from "../config";

    class UploadIMage extends Component {
      constructor(props) {
        super(props)
          this.state = { 
            selectedFile: null,
          }
      }

      // input select profile picture 
      singleFileChangedHandler = event => {
        this.setState({
          selectedFile: event.target.files[0]
        })
      }

      singleFileUploadHandler = () => {
        const data = new FormData();
        if (this.state.selectedFile) {
          data.append('image', this.state.selectedFile, this.state.selectedFile.name);
          Axios.post( `${API_BASE_URL}/user/image-upload`, data, {
            headers: {
              'accept': 'application/json',
              'Accept-Language': 'en-US, en;q=0.8',
              'Content-Type': `multipart/form-data; boundary=${data._boundary}`
            }
          })
            .then((res) => {
              if (200 === res.status) {
                if ( res.data.error ) {
                  if ('LIMIT_FILE_SIZE' === res.data.errer.code) {
                    alert('Max size: 2MB')
                  } else {
                    console.log(res.data);
                    alert(res.data.error)
                  }
                } else {
                  // Success
                  let fileName = res.data;
                  // SEND TO STATE, DISPATCH ACTION ********************
                  updateImageState(fileName)
                  alert('File Uploaded');
                }
              }
            })
              .catch((err) => {
                alert(err, 'red')
              });
        } else {
          // if file not selected throw error
          alert('Please upload file')
        }
      }

      render() { 

        return ( 

          <div>
            <div className="card border-light mb-3 mt-5" style={{ boxShadow: '0 5px 10px 2px rgba(195,192,192,.5)' }}>
              <div className="card-header">
                  <h3 style={{ color: '#555', marginLeft: '12px' }}>Single Image Upload</h3>
                  <p className="text-muted" style={{ marginLeft: '12px' }}>Upload Size: 250px x 250px ( Max 2MB )</p>
            </div>
            <div className="card-body">
              <p className="card-text">Please upload an image for your profile</p>
              <input type="file" onChange={this.singleFileChangedHandler}/>
              <div className="mt-5">
                  <button className="btn btn-info" onClick={this.singleFileUploadHandler}>Upload!</button>
              </div>
              </div>
            </div>
          </div>

        );
      }
    }

    const mapStateToProps = state => {
      return {
        
      }
    }

    const mapDispatchToProps = dispatch => {
      return bindActionCreators({
          updateImageState
      }, dispatch)
    }

    export default connect(mapStateToProps, mapDispatchToProps)(UploadIMage);

here's my github for front end https://github.com/Sebastian-Russo/avybe-challenge-profile back end https://github.com/Sebastian-Russo/profile-app-server/tree/master/profiles

So after the last couple comments about dispatching I read a little deeper into dispatching.

Everything was connected. BUT, i was calling the action directly.

WRONG (what I was doing) updateImageState()

RIGHT, (what I should have done) of this.props.updateImageState()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM