简体   繁体   中英

Unable to fetch data from Redux store and update in UI component

I am new to Redux, am building a tracker app but I have been stacked for days. I would very much appreciate it if I could get help from you. Thanks

store.js

import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

const initialState = { };
const middleware = [thunk];

const store = createStore(
  rootReducer,
  initialState,
  compose(applyMiddleware(...middleware), // store enhancer func
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()),
);

export default store;

waterReducer.js

import { GET_WATER,  ADD_WATER } from '../actions/types';

const initialState = {
  water: [],
  loading: false,
};

export default function (state = initialState, action) {                                           
  switch (action.type) {
    case GET_WATER:
      return {
        ...state,
        water: action.payload,
        loading: false,
      };
    case ADD_WATER:
      return {
        ...state,
        water: [action.payload, ...state.water || {}],
        loading: false,
      };
    default:
      return state;
  }
}


addWaterActions.js

const defaultURL = 'http://localhost:3000';

const myLibrary = JSON.parse(localStorage.getItem('myLibrary')) || []

const addWaters = waterData => async dispatch => {
  const apiConfig = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
    },
  };
  try {
    const water = await axios.post(`${defaultURL}/waters`, waterData, apiConfig);
    myLibrary.push(water.data);
    localStorage.setItem('myLibrary', JSON.stringify(myLibrary));
    dispatch({
      type: ADD_WATER,
      payload: water.data,
    });
    return water.data;

  } catch(error) {
    dispatch({
      type: WATERS_ERRORS,
      payload: error
    });
  }
};

addWaterComponent.js

import { addWaters } from '../../redux/actions/waterActions';

const AddWater = ({ addWaters }) => {
  const [formData, setFormData] = useState({
    amount: '',
    total: '',
  });
  const {
    amount, total,
  } = formData;
  const onChange = e => setFormData({ ...formData, [e.target.name]: e.target.value });

  const onSubmit = e => {
    e.preventDefault();
    addWaters({
      id: uuidv1(),
      amount,
      total,
    });
  };

  return (
    <>
      <AddWrap>
        <TrackWater>
          Add Water
        </TrackWater>
        <CenterW>
          
          <FormWrap onSubmit={onSubmit}>
            <AmountInp
              type="number"
              name="amount"
              value={amount}
              onChange={onChange}
              placeholder="Amount"
              required
            />
            <TotalInp
              type="number"
              name="total"
              placeholder="Water Target"
              value={total}
              onChange={onChange}
              required
            />
            <SubmitData type="submit" onSubmit={onSubmit}>
              Add Water to Data
            </SubmitData>
          </FormWrap>
        </CenterW>
      </AddWrap>
      <Footer />
    </>
  );
};

AddWater.propTypes = {
  addWaters: PropTypes.func.isRequired,
  water: PropTypes.array.isRequired,
};

const mapStateToProps = state => ({
  water: state.water.water,
});

export default connect(mapStateToProps, { addWaters })(AddWater);


Redux dev tools screenshot localStorage screenshot What this code has achieved 1. Dispatch data to localStorage 2. Dispatch data to Redux dev tools

My problem: I want to read the data from the store to the component, but when I console.log(store.getState().water); the state is empty. I really need your help guys. Thanks in advance

The store the js is can be configured this way const store = createStore(rootReducer,initialState, applyMiddleware(thunk)); the applyMiddleware is just an enhancer to enable you dispatch an action to your store via the reducer. console.log( action.playload ), then make sure in the reducer you equate the actual data to the water attribute. I suspect case GET_WATER: return { ...state, water: action.water, loading: false, }; should work, I suspect that is where the error is coming from, don't forget to map state to props to access data.

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