Search code examples
reactjsreduxreact-reduxaxiosredux-thunk

Why axios.get doesn't work when I use redux?


I'm creating a page with pictures from json file. It works untill I add redux. I'm a total newbie in redus so I hope you can help me to find my mistake. Thank you.

import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { getCards } from "../cardsActions";
import PortfolioItem from "../Pages/PortfolioItem";

export default function Portfolio() {

  const dispatch = useDispatch();
  const cardsListData = useSelector((state) => state.cardsList);
  const { loading, error, cards } = cardsListData;
  useEffect(() => {
    dispatch(getCards());
  }, [dispatch]);

  return (
    <div className="container">
      <div className="portfolio-wrapper">
        {loading
          ? "Loading..."
          : error
          ? error.message
          : cards.map((card) => <PortfolioItem key={card.id} {...card} />)}
      </div>
    </div>
  );
}

cardReducer.js

const initialState = {
  cards: [],
  loading: true
};

export default function (state = initialState, action) {
  switch (action.type) {
    case GET_CARDS:
      return {
        ...state,
        users: action.payload,
        loading: false
      };
    case CARDS_ERROR:
      return {
        loading: false,
        error: action.payload
      };
    default:
      return state;
  }
}

Here is the full code: https://codesandbox.io/s/naughty-mcclintock-di9bb?file=/src/cardsActions.js


Solution

  • Looks like you added your cards to the wrong key in your redux store:

    case GET_CARDS:
      return {
        ...state,
        users: action.payload, // <-- users isn't accessed in UI
        loading: false
      };
    

    You access state.cardsList.cards though. Save the payload to the cards part of your state.

    case GET_CARDS:
      return {
        ...state,
        cards: action.payload, // <-- save payload to cards state
        loading: false
      };
    

    I had to mock a JSON API endpoint, but simply swapping that out allowed me to continue tracing through your code. Barring any issues with your specific local server setup (i.e. assuming your server correctly serves up the portfolio-data.json file) this should resolve at least your updating state and UI issue.